<?php

namespace app\controllers;

use Yii;
use yii\base\Exception;
use yii\web\Controller;
use app\models\CourseInfo;
use app\models\CourseItem;
use app\models\TCourseItem;
use app\models\CourseKnowledge;
use app\models\TCourseInfo;
use app\models\BCourseItemResource;
use app\controllers\BaseController;
use app\models\TBaseClassMember;
use app\models\TCourseNote;
use app\models\BCourseInfo;
use app\models\BCourseItem;
use app\models\TCourseMember;
use Faker\Provider\Uuid;
use app\models\TQuizPaperRelation;
use app\models\TQuizPaperQuesRelation;
use app\models\TCourseScheduleQuiz;
use app\models\TQuizResult;
use app\models\BExamine;
use app\models\BCourseOpencourseteachers;
use app\models\BCourseAuthor;
use yii\helpers\Html;
/**
 * 课程接口类
 * Created by PhpStorm.
 * User: gaoyj
 * Date: 2018/5/08课堂教学查看分组详情
 */
class CourseController extends Controller {

    public $enableCsrfValidation = false;

    public function init() {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }

    public function actionCourseInfo() {
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            //课程基本信息
            $sql = "select * from b_course_info where id='".$course_id."'";
            $info = Yii::$app->db->createCommand($sql)->queryOne();
            // if ($info) {
            //     $info['content'] = Html::encode(str_replace('&nbsp;', '', strip_tags(htmlspecialchars_decode($info['content']))));
            // }
            $sql="SELECT t_base_user_id FROM b_course_author WHERE del_flag = 0 AND t_course_info_id =:courseId AND del_flag = 0 ";
            $author = \Yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course_id])->queryColumn();
            $sql="SELECT t_base_user_id FROM b_examine WHERE del_flag = 0 AND t_course_info_id =:courseId AND del_flag = 0";
            $teacher = \Yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course_id])->queryColumn();
            $authorAndTeacher=array_merge ($author,$teacher);
            $teacherTotal=array_unique($authorAndTeacher);
            empty($teacherTotal)? $teacherTotalNum=0:$teacherTotalNum=count($teacherTotal);
//            $sql = "select count(distinct resource_id) from t_resource_course where course_id='".$course_id."' and del_flag=0";
            $sql = "select count(distinct rc.resource_id) from t_resource_course rc "
                . "left join t_resource_info r on r.id=rc.resource_id "
                . "where rc.course_id='$course_id' and rc.del_flag=0 and r.del_flag=0";
            $resource = \Yii::$app->db->createCommand($sql)->queryScalar();
            $sql="SELECT
	count(*)
FROM
	t_quiz_course_ques_relation course_q
LEFT JOIN t_quiz_question q ON q.id = course_q.question_id
WHERE
	course_q.course_id =:courseId
AND q.del_flag = 0
AND course_q.del_flag = 0";
            $question =\Yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course_id])->queryScalar();
            $sql="select count(id) from t_course_task where b_course_id='".$course_id."' and t_course_id is NULL and del_flag=0";
            $task =\Yii::$app->db->createCommand($sql)->queryScalar();
            $sql="select count(id) from t_quiz_info where b_course_id='".$course_id."' and t_course_id is NULL and del_flag=0";
            $paper = \Yii::$app->db->createCommand($sql)->queryScalar();
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                "author" => $author,
                'data' => array_merge($info, array('teachersNum'=>$teacherTotalNum,'resource'=>$resource,'question'=>$question,'task'=>$task,'paper'=>$paper)),
                'code' => '200'
            );
            Yii::$app->end(json_encode($result));
        }
    }

    public function actionCourseTeachers() {
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "select t_base_user_id from b_course_author where t_course_info_id='" . $course_id . "' and is_creater=1 and del_flag=0";
            $creater = \Yii::$app->db->createCommand($sql)->queryScalar();
            $sql = "select t_base_user_id from b_course_author where t_course_info_id='" . $course_id . "' and is_creater=0 and del_flag=0";
            $editors = \Yii::$app->db->createCommand($sql)->queryColumn();
            $sql = "select t_base_user_id from b_examine where t_course_info_id='" . $course_id . "' and del_flag=0";
            $reviewers = \Yii::$app->db->createCommand($sql)->queryColumn();
            $author['creater'] = $creater;
            $author['editors'] = $editors;
            $author['reviewers'] = $reviewers;
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => $author,
                'code' => '200'
            );
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 新建课程模板接口
     * @param string  name,content,course_keyword,course_type,short_title,course_level,total_hour,major_id,major_name
     * @return mixed 错误返回空，正确返回json
     * @date: 2018-05-08
     * @author: gaoyj
     */
    public function actionSaveCourse() {
        $error = array();
        $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : $error[] = array('名称不能为空');
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : $error[] = array('内容不能为空');
        $course_keyword = isset($_REQUEST['course_keyword']) ? $_REQUEST['course_keyword'] : $error[] = array('关键字不能为空');
        $course_type = isset($_REQUEST['course_type']) ? $_REQUEST['course_type'] : $error[] = array('课程类型不能为空');
        $short_title = isset($_REQUEST['short_title']) ? $_REQUEST['short_title'] : '';
//        $course_level = isset($_REQUEST['course_level']) ? $_REQUEST['course_level'] : $error[] = array('级别不能为空');
        $total_hour = isset($_REQUEST['total_hour']) ? $_REQUEST['total_hour'] : $error[] = array('学时不能为空');
        $major_id = isset($_REQUEST['major_id']) ? $_REQUEST['major_id'] : $error[] = array('专业ID不能为空');
        $major_name = isset($_REQUEST['major_name']) ? $_REQUEST['major_name'] : $error[] = array('专业名称不能为空');
        $is_public = isset($_REQUEST['is_public']) ? $_REQUEST['is_public'] : '';
        $group_id = isset($_REQUEST['group_id']) ? $_REQUEST['group_id'] : '';
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $study_require = empty($_REQUEST['study_require']) ? '' : $_REQUEST['study_require'];
        $study_plan = empty($_REQUEST['study_plan']) ? '' : $_REQUEST['study_plan'];
        $course_lang = empty($_REQUEST['course_lang']) ? 'courseLanguage.chinese' : $_REQUEST['course_lang'];
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                // $user_id = Yii::$app->user->identity->id;
                $course = new CourseInfo();
                $uuid = Uuid::uuid();
                $course->id= $uuid;
                $course->attributes = $_REQUEST;
                $sql = "SELECT tbs.id,tbs.school_name FROM t_base_user_profile tbup left join t_base_school tbs on tbup.school_id=tbs.id WHERE tbup.user_id='" .$userId."'";
                $result = Yii::$app->db->createCommand($sql)->queryOne();
                if (!isset($_REQUEST['school']) && empty($_REQUEST['school'])) {
                    $course->school = $result['id'];
                    $course->school_name = $result['school_name'];
                }
                $course->is_exam = '0';
                $course->group_id = $group_id;
                $course->course_visibility = '是';
                if(in_array($course_type,['courseType.standard','courseType.individuation'])){
                    //标准化课程 个性化课程按照需求改为默认编辑状态需要审核
                    $course_status="courseCheckStatus.default";
                }else{
                    $course_status="courseCheckStatus.checked";
                }
                $course->course_status =$course_status;
                $course->create_by = $userId;
                $course->create_time = date("Y-m-d H:i:s", time());
                $course->is_public = $is_public;
                $course->course_lang = $course_lang;
                $course->study_plan = $study_plan;
                $course->study_require = $study_require;
                $course->total_hour = $total_hour;
                $course->project_id = $projectId;
                $course->old_id = $uuid;
                $res = $course->save();
                if ($res) {
                    $id = $course->id;
                    $old_id = $course->old_id;
                    $re = \Yii::$app->db->createCommand()->insert('b_course_author', [
                                'id'=>Uuid::uuid(),
                                't_course_info_id' => $id,
                                't_base_user_id' => $userId,
                                'is_creater' => '1',
                                'create_by' => $userId,
                                'create_time' => date("Y-m-d H:i:s", time()),
                                'del_flag' => 0,
                            ])->execute();
                    if ($re) {
                        $transaction->commit();
                        $result = [
                            'msg' => '保存成功',
                            'ver' => '1.5.0',
                            'data' => [
                                'courseCode' => $old_id,
                            ],
                            'code' => '200'
                        ];
                    } else {
                        $transaction->rollback();
                        $result = [
                            'msg' => '保存失败',
                            'ver' => '1.5.0',
                            'data' => [
                            ],
                            'code' => '400'
                        ];
                    }
                    Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
                } else {
                    $transaction->rollback();
                    $result = [
                        'msg' => '保存失败',
                        'ver' => '1.5.0',
                        'data' => [$course->errors
                        ],
                        'code' => '400'
                    ];
                }
                Yii::$app->end(json_encode($result['data'][0], JSON_UNESCAPED_UNICODE));
            } catch (Exception $e) {
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
            }
        }
    }

    /**
     * 审核课程接口
     * @param int  courseIds:课程ID userId:用户ID
     * @return mixed 错误返回空，正确返回json
     * @date: 2018-06-14
     * @author: gaoyj
     */
    public function actionCheckCourse() {
        $error = array();
        $courseIds = isset($_REQUEST['courseIds']) ? $_REQUEST['courseIds'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        } else {
            $sql = "UPDATE b_course_info SET course_status='courseCheckStatus.checking',update_by=:update_by,update_time=:update_time WHERE id=:id AND del_flag=0";
            $params = [':id' => $courseIds, ':update_by' => $userId, 'update_time' => date("Y-m-d H:i:s", time())];
            $res = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->execute();
            if ($res) {
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'flag' => '1',
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [
                        'flag' => '0',
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 审核通过课程接口
     * @param int  courseIds:课程ID userID:用户ID
     * @return mixed 错误返回空，正确返回json
     * @date: 2018-06-14
     * @author: gaoyj
     */
    public function actionCheckThroughCourse() {
        $error = array();
        $courseIds = isset($_REQUEST['courseIds']) ? $_REQUEST['courseIds'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('审核状态不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        } else {
            if ($type == 'pass') {
                $status = "courseCheckStatus.checked";
            } elseif ($type == 'no_pass') {
                $status = "courseCheckStatus.notPass";
            }
            $sql = "UPDATE b_course_info SET course_status='$status',update_by=:update_by,update_time=:update_time WHERE id in('".implode("','", explode(',', $courseIds))."') AND del_flag=0";
            $params = ['update_by' => $userId, 'update_time' => date("Y-m-d H:i:s", time())];
            $res = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->execute();
            if ($res) {
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'flag' => '1',
                        'courseIds'=>explode(',', $courseIds)
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [
                        'flag' => '0',
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }
    /*'
     *  模板课课程结束 和 重新开启 功能
     * jhy
     */
    public function actionFinishBcourse(){
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('类型不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        } else {
            $model = BCourseInfo::findOne($courseId);
            $model->course_status=$type;
            $model->update_by=$userId;
            $model->update_time=date("Y-m-d H:i:s", time());
            if($model->validate() && $model->save()){
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'flag' => '1',
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            }else{
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => $model->errors,
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 审核通过课程接口
     * @param int  courseIds:课程ID userID:用户ID
     * @return mixed 错误返回空，正确返回json
     * @date: 2018-06-14
     * @author: gaoyj
     */
    public function actionCheckCourseStatus() {
        $error = array();
        $courseIds = isset($_REQUEST['courseIds']) ? $_REQUEST['courseIds'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('类型不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        } else {
            $update_time=date("Y-m-d H:i:s", time());
//            $sql = "UPDATE t_course_info SET course_status='" . $type . "',update_by=:update_by,update_time=:update_time WHERE id=:id AND del_flag=0";
//            $params = [':id' => $courseIds, 'update_by' => $userId, 'update_time' =>$update_time];
//            $res = Yii::$app->db->createCommand($sql)
//                    ->bindValues($params)
//                    ->execute();
            $model = TCourseInfo::findOne($courseIds);
            $model->course_status = $type;
            $model->update_by=$userId;
            $model->update_time = $update_time;
            if ($model->validate() && $model->save()) {
//                $sql="select create_time from t_course_info where id='".$courseIds."' and del_flag=0";
//                $res=\yii::$app->db->createCommand($sql)->queryAll();
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'flag' => '1',
                        'update_time'=>$update_time,
                        'start_time'=>$model->create_time,
                        'bcourseId'=>$model->b_course_info_id,
                        'b_old_id'=>$model->old_id
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [
                        'flag' => '0',
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 删除课程模板接口
     * @param int  courseIds 课程ID userId:用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-09
     * @author: gaoyj
     */
    public function actionDeleteCourse() {
        $error = array();
        $courseIds = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (empty($error)) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $update_time=date("Y-m-d H:i:s", time());
                $sql = "UPDATE b_course_info SET del_flag=1,update_by='" . $userId . "',update_time='" .$update_time. "' WHERE id IN('" . implode("','", explode(',', $courseIds)). "') ";
                $res = \Yii::$app->db->createCommand($sql)->execute();
                if ($res) {
                    $sql1 = "UPDATE b_course_author SET del_flag=1,update_by='" . $userId . "',update_time='" . $update_time. "' WHERE t_course_info_id IN('" . implode("','", explode(',', $courseIds)). "') ";
                    $res1 = \Yii::$app->db->createCommand($sql1)->execute();
                    if ($res1) {
                        $transaction->commit();
                        $result = [
                            'msg' => '删除成功',
                            // 'ver' => $_REQUEST['ver'],
                            'data' => [
                                'flag' => '1',
                                'update_time'=>$update_time
                            ],
                            'code' => '200'
                        ];
                    } else {
                        $transaction->rollback();
                        $result = [
                            'msg' => '删除失败',
                            // 'ver' => $_REQUEST['ver'],
                            'data' => [
                                'flag' => '0',
                            ],
                            'code' => '400'
                        ];
                    }
                    Yii::$app->end(json_encode($result));
                } else {
                    $transaction->rollback();
                    $result = [
                        'msg' => '删除失败',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => [
                            'flag' => '0',
                        ],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            } catch (Exception $e) {
                $result = [
                    'msg' => '删除失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'flag' => '0',
                    ],
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        } else {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 结束课程模板接口
     * @param int  courseIds 课程ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-10
     * @author: gaoyj
     */
    public function actionFinishCourse() {
        $error = array();
        $courseIds = isset($_REQUEST['courseIds']) ? $_REQUEST['courseIds'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (empty($error)) {
            $id = explode(',', $courseIds);
            $transaction = Yii::$app->db->beginTransaction();
            foreach ($id as $key => $val) {
                $res = \Yii::$app->db->createCommand()->update('b_course_info', ['course_status' => 'courseCheckStatus.finish', 'update_by' => $userId, 'update_time' => date("Y-m-d H:i:s", time())], 'id=:id', [':id' => $val])->execute();
                if ($res) {
                    $flag = 1;
                } else {
                    $flag = 0;
                    break;
                }
            }
            if ($flag == 1) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        } else {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 开课结束课程接口
     * @param int  courseIds 课程ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-10
     * @author: gaoyj
     */
    public function actionOpenCourseFinishCourse() {
        $error = array();
        $courseIds = isset($_REQUEST['courseIds']) ? $_REQUEST['courseIds'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] :'';
        if (empty($error)) {
            $id = explode(',', $courseIds);
            $transaction = Yii::$app->db->beginTransaction();
            $update_time=date("Y-m-d H:i:s", time());
            foreach ($id as $key => $val) {
                $res = \Yii::$app->db->createCommand()->update('t_course_info', ['course_status' => 'courseCheckStatus.finish', 'update_by' => $userId, 'update_time' => $update_time], 'id=:id', [':id' => $val])->execute();
                if ($res) {
                    $flag = 1;
                } else {
                    $flag = 0;
                    break;
                }
            }
            if ($flag == 1) {
                $transaction->commit();
                $create_time='';
                if($type=='details'){
                    $sql="select create_time from t_course_info where update_by='".$userId."' and id='".$courseIds."'";
                    $create_time=\yii::$app->db->createCommand($sql)->queryOne();
                }
                $result = [
                    'msg' => '操作成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'create_time'=>$create_time
                    ],
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        } else {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 开课删除课程接口
     * @param int  courseIds 课程ID userId:用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-09
     * @author: gaoyj
     */
    public function actionOpenCourseDeleteCourse() {
        $error = array();
        $courseIds = isset($_REQUEST['courseIds']) ? $_REQUEST['courseIds'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (empty($error)) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $update_time=date("Y-m-d H:i:s", time());
                $sql = "UPDATE t_course_info SET del_flag=1,update_by='" . $userId . "',update_time='" . $update_time . "' WHERE id IN(" . $courseIds . ") ";
                $res = \Yii::$app->db->createCommand($sql)->execute();
                if($res){
                  $transaction->commit();
                    $result = [
                        'msg' => '删除成功',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => ['update_time'=>$update_time],
                        'code' => '200'
                    ];
                }else{
                  $transaction->rollBack();
                    $result = [
                        'msg' => '删除失败',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => [],
                        'code' => '400'
                    ];
                }
                Yii::$app->end(json_encode($result));
            } catch (Exception $e) {
                $result = [
                    'msg' => '删除失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'flag' => '0',
                    ],
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        } else {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 添加课程单元章节接口
     * @param string  title:单元名称 type:类型
     * @param int  pid:单元章节父ID courseId:课程ID userId:用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-10
     * @author: gaoyj
     */
    public function actionSaveCourseChapter() {
        $error = array();
        $title = isset($_REQUEST['title']) ? $_REQUEST['title'] : $error[] = array('单元名称不能为空');
        $pid = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : $error[] = array('父id不能为空');
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('类型不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sequence = CourseItem::find()->select('sequence')->asArray()->where(['pid' => $pid, 'del_flag' => 0])->orderBy('sequence desc')->limit(1)->one();
            if ($sequence) {
                $sequence = intval($sequence['sequence']) + 1;
            } else {
                $sequence = 1;
            }
            $uuid = Uuid::uuid();
            $course_item = new CourseItem;
            $course_item->id= $uuid;
            $course_item->attributes = $_REQUEST;
            $course_item->sequence = $sequence;
            $course_item->course_id = $courseId;
            $course_item->create_by = $userId;
            $course_item->create_time = date("Y-m-d H:i:s", time());
            $course_item->state = 'courseItemState.Unpublished';
            $course_item->del_flag = 0;
            $course_item->old_id = $uuid;
            if ($course_item->save()) {
                $result = [
                    'msg' => '保存成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'flag' => '1',
                        'id'=>$course_item->id
                    ],
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            } else {
                $result = [
                    'msg' => '保存失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'flag' => '0',
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }

    /**
     * 保存 节的信息
     */
    public function actionSaveCourseSection() {
        $error = array();
        $title = isset($_REQUEST['title']) ? $_REQUEST['title'] : $error[] = array('单元名称不能为空');
        $pid = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : $error[] = array('父id不能为空');
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('类型不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = 'select sequence from (select id,sequence from b_course_item where course_id="' . $courseId . '" and del_flag=0 and pid="' . $pid .'" UNION select id,sequence from b_course_item_resource_reference where course_id="' . $courseId .'" and del_flag=0 and item_id="'.$pid .'") as table1 
                    order by sequence desc limit 1';
            $sequence = \Yii::$app->db->createCommand($sql)->queryScalar();
            if (empty($sequence)) {
                $sequence = 1;
            } else {
                $sequence++;
            }
            $uuid= Uuid::uuid();
            $course_item = new CourseItem;
            $course_item->id= $uuid;
            $course_item->attributes = $_REQUEST;
            $course_item->sequence = $sequence;
            $course_item->course_id = $courseId;
            $course_item->create_by = $userId;
            $course_item->create_time = date("Y-m-d H:i:s", time());
            $course_item->state = 'courseItemState.Unpublished';
            $course_item->del_flag = 0;
            $course_item->old_id = $uuid;
            if ($course_item->save()) {
                $result = [
                    'msg' => '保存成功',
                    'data' => [
                        'flag' => '1',
                        'id'=>$course_item->id
                    ],
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            } else {
                $result = [
                    'msg' => '保存失败',
                    'data' => [
                        'flag' => '0',
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }

    /**
     * 修改课程单元章节接口
     * @param string  title:单元名称
     * @param int  id:章节ID userId:用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-11
     * @author: gaoyj
     */
    public function actionUpdateCourseChapter() {
        $error = array();
        $title = isset($_REQUEST['title']) ? $_REQUEST['title'] : $error[] = array('单元名称不能为空');
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : $error[] = array('id不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "UPDATE b_course_item SET title=:title,update_by=:userId,update_time=:update_time WHERE id=:id";
            $params = [':title' => $title, ':userId' => $userId, ':id' => $id, ':update_time' => date("Y-m-d H:i:s", time())];
            $res = \Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->execute();
            if ($res) {
                $result = [
                    'msg' => '保存成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'flag' => '1',
                    ],
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            } else {
                $result = [
                    'msg' => '保存失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'flag' => '0',
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }

    /**
     * 删除课程模板章节接口
     * @param int  courseId:课程ID userId:用户ID
     * @param int  itemId:章节ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-14
     * @author: gaoyj
     */
    public function actionDeleteCourseItem() {
        $error = array();
        $itemId = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : $error[] = array('章节ID不能为空');
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        } else {
            $resources = BCourseItemResource::find()->where(['item_id' => $itemId, 'del_flag' => 0])->all();
            if ($resources) {
                $result = [
                    'msg' => '该章节下有资源，不能删除',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
            }

            $item = CourseItem::find()->where(['pid' => $_REQUEST['itemId'], 'del_flag' => 0])->asArray()->all();
            if ($item) {
                $result = [
                    'msg' => '此节点下有其它节点，不能删除',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
            } else {
                $sql = "UPDATE b_course_item SET del_flag=1,update_by=:update_by,update_time=:update_time WHERE id=:id AND course_id=:courseId";
                $params = [':courseId' => $courseId, 'update_by' => $userId, 'update_time' => date("Y-m-d H:i:s", time()), 'id' => $itemId];
                $res = \Yii::$app->db->createCommand($sql)
                        ->bindValues($params)
                        ->execute();
                if ($res) {
                    $result = [
                        'msg' => '操作成功',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => [
                        ],
                        'success' => true,
                        'code' => '200'
                    ];
                } else {
                    $result = [
                        'msg' => '操作失败',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => [
                        ],
                        'success' => false,
                        'code' => '400'
                    ];
                }
                Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
            }
        }
    }

    /**
     * 添加知识点接口
     * @param string  name:知识点名称 content:知识点内容
     * @param int  itemId:章节ID courseId:课程ID userId:用户ID id:知识点ID（如果传id就是更新）
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-10
     * @author: gaoyj
     */
    public function actionSaveCourseKnowledge() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $itemId = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : $error[] = array('章节ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : $error[] = array('知识点名称不能为空');
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : $error[] = array('知识点内容不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                if (!empty($_REQUEST['id'])) {
                    $course_knowledge = CourseKnowledge::findOne($_REQUEST['id']);
                    $course_knowledge->attributes = $_REQUEST;
                    $course_knowledge->course_id = $courseId;
                    $course_knowledge->update_by = $userId;
                    $course_knowledge->update_time = date("Y-m-d H:i:s", time());
                    if ($course_knowledge->save()) {
                        $transaction->commit();
                        $result = [
                            'msg' => '操作成功',
                            // 'ver' => $_REQUEST['ver'],
                            'data' => [
                                'knowledgeId' => $course_knowledge->attributes['id'],
                            ],
                            'code' => '200'
                        ];
                        Yii::$app->end(json_encode($result));
                    } else {
                        $transaction->rollback();
                        $result = [
                            'msg' => '操作失败',
                            // 'ver' => $_REQUEST['ver'],
                            'data' => [
                            ],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
                $course_knowledge = new CourseKnowledge;
                $course_knowledge->attributes = $_REQUEST;
                $course_knowledge->course_id = $courseId;
                $course_knowledge->create_by = $userId;
                $course_knowledge->create_time = date("Y-m-d H:i:s", time());
                if ($course_knowledge->save()) {
                    $point_id = $course_knowledge->attributes['id'];
                    $res = Yii::$app->db->createCommand()->insert('b_course_item_knowledge_point_relation', [
                                'item_id' => $itemId,
                                'point_id' => $point_id,
                            ])->execute();
                    if ($res) {
                        $transaction->commit();
                        $result = [
                            'msg' => '操作成功',
                            // 'ver' => $_REQUEST['ver'],
                            'data' => [
                                'knowledgeId' => $point_id
                            ],
                            'code' => '200'
                        ];
                        Yii::$app->end(json_encode($result));
                    } else {
                        $transaction->rollback();
                        $result = [
                            'msg' => '操作失败',
                            // 'ver' => $_REQUEST['ver'],
                            'data' => [
                            ],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                } else {
                    $result = [
                        'msg' => '操作失败',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => [
                        ],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            } catch (Exception $e) {
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }

    /**
     * 根据章节id查询知识点列接口
     * @param int  page:当前页码 pageSize:每一页行数
     * @param int  itemId:章节ID courseId:课程ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-11
     * @author: gaoyj
     */
    public function actionGetKnowledgeListByItem() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $itemId = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : $error[] = array('章节ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (empty($error)) {
            $pageSize = isset($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '20';
            $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';
            $limit = "limit " . ($page - 1) * $pageSize . ",$pageSize";
            // $sql = "SELECT bck.* FROM b_course_item_knowledge_point_relation bci LEFT JOIN b_course_knowledge_point bck ON bci.point_id=bck.id WHERE bck.course_id=".$_REQUEST['courseId']." AND bci.item_id=".$_REQUEST['itemId']." ".$limit."";
            $sql = "SELECT bck.* FROM b_course_item_knowledge_point_relation bci LEFT JOIN b_course_knowledge_point bck ON bci.point_id=bck.id WHERE bck.course_id=:id AND bck.del_flag=0 AND bci.item_id=:itemId " . $limit . "";
            $params = [':id' => $_REQUEST['courseId'], ':itemId' => $_REQUEST['itemId']];
            $data = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->queryAll();
            if ($data) {
                $result = [
                    'msg' => '查找成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'list' => $data,
                    ],
                    'success' => 'true',
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            } else {
                $result = [
                    'msg' => '查找失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => 'false',
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        } else {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 根据章节id查询子章节接口
     * @param int  itemId:章节ID courseId:课程ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-11
     * @author: gaoyj
     */
    public function actionGetChildrenCourseChapter() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $itemId = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : $error[] = array('章节ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
//    		$sql = "SELECT * FROM b_course_item WHERE course_id=:id AND id=:itemId OR pid=:itemId AND del_flag=0";
            $sql = "SELECT * FROM b_course_item WHERE course_id=:id AND id in (" . $itemId . ")  AND del_flag=0";
            $params = [':id' => $courseId];
            $res = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->queryAll();
            if (!empty($res)) {
                $item = CourseItem::findOne($itemId);
                if ($item->del_flag == 0) {
                    $data = $this->GetSonTree($res, $item->pid);
                    $result = [
                        'msg' => '查找成功',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => [
                            'list' => $data,
                        ],
                        'code' => '200'
                    ];
                } else {
                    $result = [
                        'msg' => '查找失败',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => [
                        ],
                        'code' => '400'
                    ];
                }
                Yii::$app->end(json_encode($result));
            } else {
                $result = [
                    'msg' => '查找失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }

    //根据id查询素材信息
    public function actionGetChildrenCourseResource() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $resourceId = isset($_REQUEST['resourceId']) ? $_REQUEST['resourceId'] : $error[] = array('章节ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "SELECT * FROM b_course_item_resource_reference WHERE course_id=:id AND id in (" . $resourceId . ")  AND del_flag=0";
            $params = [':id' => $courseId];
            $res = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->queryAll();
            if (!empty($res)) {
                $result = [
                    'msg' => '查找成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => $res,
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            } else {
                $result = [
                    'msg' => '查找失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }

    public function GetSonTree($data, $pid = 0, $field = 'id') {
        $newData = [];
        if ($data) {
            foreach ($data as $key => $val) {
                if ($val['pid'] == $pid) {
                    $newData[$key] = $val;
                    $newData[$key]['childrenCourseItems'] = $this->GetSonTree($data, $val[$field], $field);
                }
            }
            return $newData;
        }
    }

    /**
     * 根据课程id查询课程大纲接口
     * @param int  courseId:课程ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-14
     * @author: gaoyj
     */
    public function actionGetCourseOutline() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : '';
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $res = CourseItem::find()->where(['course_id' => $courseId, 'del_flag' => 0])->asArray()->all();

            if ($res) {
                $data = $this->GetSonTree($res, 0);
                $result = [
                    'msg' => '查找成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'list' => $data,
                    ],
                    'code' => '200',
                ];
            } else {
                $result = [
                    'msg' => '查找失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'code' => '400',
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 章节添加资源接口
     * @param int  resourseId:资源ID itemId:章节ID userId:用户ID
     * @param string  type:资源类型
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-14
     * @author: gaoyj
     */
    public function actionChapterJoinResource() {
        $error = array();
        $resourseId = isset($_REQUEST['resourseId']) ? $_REQUEST['resourseId'] : $error[] = array('资源ID不能为空');
        $itemId = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : $error[] = array('章节ID不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('资源类型不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $course = CourseItem::findOne($_REQUEST['itemId']);
            if ($course) {
                $courseId = $course->course_id;
            } else {
                $courseId = '';
            }
            $sort = BCourseItemResource::find()->select('sequence')->asArray()->where(['item_id' => $itemId])->orderBy('sequence desc')->limit(1)->one();
            $sort = intval($sort['sequence']);

            $resourseId = explode(',', $resourseId);
            $type = explode(',', $type);
            $values = '';
            for ($i = 0; $i < count($resourseId); $i++) {
                $values .= "(" . $resourseId[$i] . ",'" . $type[$i] . "'," . $itemId . "," . $courseId . "," . $userId . ",'" . date("Y-m-d H:i:s", time()) . "',0," . ($sort + $i + 1) . "),";
            }
            $values = rtrim($values, ',');
            $sql = "INSERT INTO b_course_item_resource_reference (resourse_id,type,item_id,course_id,create_by,create_time,del_flag,sequence) VALUES " . $values . "";
            $res = Yii::$app->db->createCommand($sql)->execute();
            if ($res === count($resourseId)) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 开课添加章节接口
     * @param int  courseId:课程ID itemId:章节ID userId:用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-17
     * @author: gaoyj
     */
    public function actionAddCourseChapter() {
        $error = array();
        $itemIds = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : '';
        $resourceIds = isset($_REQUEST['resourceIds']) ? $_REQUEST['resourceIds'] : '';
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $itemId = explode(',', $itemIds);
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                foreach ($itemId as $key => $val) {
                    $sql = "INSERT INTO t_course_item (template_course_item,pid,type,title,content,state,course_id,create_by,del_flag,create_time,sequence) SELECT id,pid,type,title,content,state," . $courseId . " as course_id," . $userId . " as create_by,0,create_time,sequence FROM b_course_item WHERE id=" . $val . "";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    $id = Yii::$app->db->getLastInsertID();

                    if ($res) {
                        $sql1 = "SELECT resourse_id,type," . $id . " as item_id,course_id FROM b_course_item_resource_reference where item_id=" . $val . " AND del_flag=0";
                        $data = Yii::$app->db->createCommand($sql1)->queryAll();
                        if ($data) {
                            $sql2 = "INSERT INTO t_course_item_resource_reference (resourse_id,type,item_id,course_id,create_by,del_flag,create_time) SELECT resourse_id,type," . $id . " as item_id," . $courseId . " as course_id," . $userId . " as create_by,del_flag,create_time FROM b_course_item_resource_reference WHERE item_id=" . $val . " AND del_flag=0 and id in (" . $resourceIds . ")";
                            $res2 = Yii::$app->db->createCommand($sql2)->execute();
                            if (!$res2) {
                                $flag = 1;
                                break;
                            }
                        }
                    } else {
                        $flag = 1;
                        break;
                    }
                }
            } catch (Exception $e) {
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    //开课保存章
    public function actionStartCourseSaveCourseCatalog() {
        $error = array();
        $itemIds = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : '';
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                $sql = "select * from t_course_item where course_id=" . $courseId . " and template_course_item=" . $itemIds;
                $res = Yii::$app->db->createCommand($sql)->queryAll();
                if (!empty($res)) {
                    //原来该课程下已经存在该章节 先逻辑删除
                    $sql = "update t_course_item set del_flag=1 where course_id=" . $courseId . " and template_course_item=" . $itemIds;
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res) {
                        $flag = 1;
                    }
                }
                $sql = "INSERT INTO t_course_item (template_course_item,pid,type,title,content,state,course_id,create_by,del_flag,create_time,sequence) SELECT id,0 as pid,type,title,content,state," . $courseId . " as course_id," . $userId . " as create_by,0,create_time,sequence FROM b_course_item WHERE id=" . $itemIds . "";
                $res = Yii::$app->db->createCommand($sql)->execute();
                if (!$res) {
                    $flag = 1;
                }
            } catch (Exception $e) {
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    //开课保存节
    public function actionStartCourseSaveCourseChapter() {
        $error = array();
        $itemIds = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : '';
        $pid = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : '';
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                $sql = "select * from t_course_item where course_id=" . $courseId . " and template_course_item=" . $itemIds;
                $res = Yii::$app->db->createCommand($sql)->queryAll();
                if (!empty($res)) {
                    //原来该课程下已经存在该节 先逻辑删除
                    $sql = "update t_course_item set del_flag=1 where course_id=" . $courseId . " and template_course_item=" . $itemIds;
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res) {
                        $flag = 1;
                    }
                }
                $sql = "INSERT INTO t_course_item (template_course_item,pid,type,title,content,state,course_id,create_by,del_flag,create_time,sequence) SELECT id,(select id from t_course_item where template_course_item=" . $pid . " order by id desc limit 1 ) as pid,type,title,content,state," . $courseId . " as course_id," . $userId . " as create_by,0,create_time,sequence FROM b_course_item WHERE id=" . $itemIds . "";
                $res = Yii::$app->db->createCommand($sql)->execute();
                if (!$res) {
                    $flag = 1;
                }
            } catch (Exception $e) {
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    //开课保存素材
    public function actionStartCourseSaveResource() {
        $error = array();
        $itemIds = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : '';
        $pid = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : '';
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                $sql = "select * from t_course_item_resource_reference where course_id=" . $courseId . " and resourse_id=(select resourse_id from b_course_item_resource_reference where id=" . $itemIds . ")";
                $res = Yii::$app->db->createCommand($sql)->queryAll();
                if (!empty($res)) {
                    //原来该课程下已经存在素材 先逻辑删除
                    $sql = "update t_course_item_resource_reference set del_flag=1 where course_id=" . $courseId . " and resourse_id=(select resourse_id from b_course_item_resource_reference where id=" . $itemIds . ")";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res) {
                        $flag = 1;
                    }
                }
                $sql2 = "INSERT INTO t_course_item_resource_reference (resourse_id,type,template_item_id,item_id,course_id,create_by,del_flag,create_time) SELECT resourse_id,type,$itemIds as template_item_id,(select id from t_course_item where template_course_item=" . $pid . " order by id desc limit 1) as item_id," . $courseId . " as course_id," . $userId . " as create_by,del_flag,create_time FROM b_course_item_resource_reference WHERE  del_flag=0 and id=" . $itemIds;
                $res2 = Yii::$app->db->createCommand($sql2)->execute();
                if (!$res2) {
                    $flag = 1;
                }
            } catch (Exception $e) {
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    //保存章节素材
    public function actionSaveChapterOrResource() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $data_ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : '';
        $ids = json_decode($data_ids, true);
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
//            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                if (!empty($ids)) {
                    //若存在该章节则逻辑删除
                    $sql = "update t_course_item set del_flag=1 where course_id='" . $courseId."'";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res && $res != 0) {
                        $flag = 1;
                    }
                    //若存在该素材则逻辑删除
                    $sql = "update t_course_item_resource_reference set del_flag=1 where course_id='" . $courseId."'";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res && $res != 0) {
                        $flag = 1;
                    }
                    //按level从小到大排序,确保先保存章然后保存节最后保存素材
                    foreach ($ids as $key => $row) {
                        $volume[$key] = $row['level'];
                    }
                    array_multisort($volume, SORT_ASC, $ids);
                    foreach ($ids as $key => $value) {
                        if ($value['level'] == 1) {
                            //保存章
                            $zhang_id = $value['id'];
                            $sql="select * from b_course_item where id='".$zhang_id."'";
                            $itemData = \Yii::$app->db->createCommand($sql)->queryOne();
                            $zhang_model = new TCourseItem();
                            $zhang_model->id= Uuid::uuid();
                            $zhang_model->template_course_item=$itemData['id'];
                            $zhang_model->pid='0';
                            $zhang_model->type =$itemData['type'];
                            $zhang_model->title=$itemData['title'];
                            $zhang_model->content=$itemData['content'];
                            $zhang_model->state=$itemData['state'];
                            $zhang_model->course_id=$courseId;
                            $zhang_model->create_by=$userId;
                            $zhang_model->create_time = date('Y-m-d H:i:s');
                            $zhang_model->sequence=$itemData['sequence'];
                            $zhang_model->del_flag=0;
                            if(!$zhang_model->save()){
                                $flag=1;
                                
                            }else{
                                
                            }
//                            $sql = "INSERT INTO t_course_item (id,template_course_item,pid,type,title,content,state,course_id,create_by,del_flag,create_time,sequence) SELECT '".Uuid::uuid()."',id,0 as pid,type,title,content,state,'" . $courseId . "' as course_id,'" . $userId . "' as create_by,0,create_time,sequence FROM b_course_item WHERE id='" . $zhang_id . "'";
//                            $res = Yii::$app->db->createCommand($sql)->execute();
//                            if (!$res) {
//                                $flag = 1;
//                            }
                        }
                        if ($value['level'] == 2) {
                            //保存小节或素材
                            if ($value['type'] == 'file') {
                                $resourceId = $value['id'];
                                $pid = $value['pid'];
                                
                                $sql="select id from t_course_item where template_course_item='" . $pid . "' and course_id='".$courseId."' and del_flag=0 order by id desc limit 1";
                                $item_id = Yii::$app->db->createCommand($sql)->queryScalar();
                                $row_data ="SELECT resourse_id,title,type,create_by,del_flag,create_time,sequence FROM b_course_item_resource_reference WHERE  del_flag=0 and id='" . $resourceId."'";
                                $row_data= Yii::$app->db->createCommand($row_data)->queryOne();
                                //保存素材
                                
                                $model = new \app\models\TCourseItemResourceReference();
                                $model -> id = Uuid::uuid();
                                $model->resourse_id = $row_data['resourse_id'];
                                $model->title = $row_data['title'];
                                $model->type = $row_data['type'];
                                $model->template_item_id = $resourceId;
                                $model->item_id = $item_id;
                                $model->course_id= $courseId;
                                $model->create_by = $userId;
                                $model->del_flag=0;
                                $model->create_time=date("Y-m-d H:i:s");
                                $model->sequence = $row_data['sequence'];
                                if(!$model->save()){
                                    $flag=1;
                                }
//                                $sql = "INSERT INTO t_course_item_resource_reference (id,resourse_id,type,template_item_id,item_id,course_id,create_by,del_flag,create_time,sequence) SELECT '".Uuid::uuid()."',resourse_id,type,'".$resourceId."' as template_item_id,(select id from t_course_item where template_course_item='" . $pid . "' and course_id='".$courseId."' and del_flag=0 order by id desc limit 1) as item_id,'" . $courseId . "' as course_id,'" . $userId . "' as create_by,del_flag,create_time,sequence FROM b_course_item_resource_reference WHERE  del_flag=0 and id='" . $resourceId."'";
//                                $res = Yii::$app->db->createCommand($sql)->execute();
//                                if (!$res) {
//                                    $flag = 1;
//                                }
                            } else {
                                $jie_id = $value['id'];
                                $pid = $value['pid'];
                                
                                $pid_sql="select id from t_course_item where template_course_item='" . $pid . "' and course_id='".$courseId."' and del_flag=0  order by id desc limit 1 ";
                                $pid = Yii::$app->db->createCommand($pid_sql)->queryScalar();
                                $row_data_sql="SELECT id,type,title,content,state,create_time,sequence FROM b_course_item WHERE id='" . $jie_id . "'";
                                $row_data = Yii::$app->db->createCommand($row_data_sql)->queryOne();
                                //保存小节
                                $jie_model = new TCourseItem();
                                $jie_model->id= Uuid::uuid();
                                $jie_model->template_course_item=$row_data['id'];
                                $jie_model->pid=$pid;
                                $jie_model->type =$row_data['type'];
                                $jie_model->title=$row_data['title'];
                                $jie_model->content=$row_data['content'];
                                $jie_model->state=$row_data['state'];
                                $jie_model->course_id=$courseId;
                                $jie_model->create_by=$userId;
                                $jie_model->create_time = date('Y-m-d H:i:s');
                                $jie_model->sequence=$row_data['sequence'];
                                $jie_model->del_flag=0;
                                if(!$jie_model->save()){
                                    $flag = 1;
                                }
//                                $sql = "INSERT INTO t_course_item (id,template_course_item,pid,type,title,content,state,course_id,create_by,del_flag,create_time,sequence) SELECT '".Uuid::uuid()."',id,(select id from t_course_item where template_course_item='" . $pid . "' and course_id='".$courseId."' and del_flag=0  order by id desc limit 1 ) as pid,type,title,content,state,'" . $courseId . "' as course_id,'" . $userId . "' as create_by,0,create_time,sequence FROM b_course_item WHERE id='" . $jie_id . "'";
//                                $res = Yii::$app->db->createCommand($sql)->execute();
//                                if (!$res) {
//                                    $flag = 1;
//                                }
                            }
                        }
                        if ($value['level'] == 3) {
                            //保存素材
                            $resourceId = $value['id'];
                            $pid = $value['pid'];
                            $pid_sql="select id from t_course_item where template_course_item='" . $pid . "' and course_id='".$courseId."' and del_flag=0  order by id desc limit 1";
                            $item_id = Yii::$app->db->createCommand($pid_sql)->queryScalar();
                            $row_data_sql="SELECT resourse_id,type,title,del_flag,create_time,sequence FROM b_course_item_resource_reference WHERE  del_flag=0 and id='" . $resourceId."'";
                            $row_data = Yii::$app->db->createCommand($row_data_sql)->queryOne();
                            $model = new \app\models\TCourseItemResourceReference();
                            $model -> id = Uuid::uuid();
                            $model->resourse_id = $row_data['resourse_id'];
                            $model->title = $row_data['title'];
                            $model->type = $row_data['type'];
                            $model->template_item_id = $resourceId;
                            $model->item_id = $item_id;
                            $model->course_id= $courseId;
                            $model->create_by = $userId;
                            $model->del_flag=0;
                            $model->create_time=date("Y-m-d H:i:s");
                            $model->sequence = $row_data['sequence'];
                            if(!$model->save()){
                                $flag=1;
                            }
//                            $sql = "INSERT INTO t_course_item_resource_reference (id,resourse_id,type,template_item_id,item_id,course_id,create_by,del_flag,create_time,sequence) SELECT '".Uuid::uuid()."',resourse_id,type,'".$resourceId."' as template_item_id,(select id from t_course_item where template_course_item='" . $pid . "' and course_id='".$courseId."' and del_flag=0  order by id desc limit 1) as item_id,'" . $courseId . "' as course_id,'" . $userId . "' as create_by,del_flag,create_time,sequence FROM b_course_item_resource_reference WHERE  del_flag=0 and id='" . $resourceId."'";
//                            $res = Yii::$app->db->createCommand($sql)->execute();
//                            if (!$res) {
//                                $flag = 1;
//                            }
                        }
                    }
                } else {
                    //未选择章节素材
                    $sql = "update t_course_item set del_flag=1 where course_id='" . $courseId."'";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res && $res != 0) {
                        $flag = 1;
                    }
                    //未选择章节素材
                    $sql = "update t_course_item_resource_reference set del_flag=1 where course_id='" . $courseId."'";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res && $res != 0) {
                        $flag = 1;
                    }
                }
            } catch (Exception $e) {
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($flag == 0) {
//                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
//                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 查询课程下的所有班级接口
     * @param int  major_id:专业ID school_id:学校ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-21
     * @author: gaoyj
     */
    public function actionGetCourseClass() {
        $error = array();
        $majorId = isset($_REQUEST['major_id']) ? $_REQUEST['major_id'] : $error[] = array('专业ID不能为空');
        $schoolId = isset($_REQUEST['school_id']) ? $_REQUEST['school_id'] : $error[] = array('学校ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "SELECT tbc.*,tbs.school_name,tbd.name as department_name,tbm.name as major_name,(SELECT COUNT(*) FROM t_base_class_member tbcm WHERE tbc.id=tbcm.class_id) as num FROM t_base_class tbc 
					LEFT JOIN t_base_school tbs ON tbc.school_id=tbs.id 
					LEFT JOIN t_base_department tbd ON tbc.department_id=tbd.id 
					LEFT JOIN t_base_major tbm ON tbc.major_id=tbm.id 
					WHERE tbc.major_id=:major_id AND tbc.school_id=:school_id AND tbc.del_flag=0";
            $params = [':major_id' => $majorId, ':school_id' => $schoolId];
            $list = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->queryAll();
            if ($list) {
                $result = [
                    'msg' => '查找成功',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                        'list' => $list,
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '查找失败',
                    // 'ver' => $_REQUEST['ver'],
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 开课选择班级接口
     * @param int  class_id:班级ID course_id:课程ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-05-22
     * @author: gaoyj
     */
    public function actionClassesChooseClass() {
        $error = array();
        $classId = isset($_REQUEST['classId']) ? $_REQUEST['classId'] : $error[] = array('班级ID不能为空');
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $uid = isset($_REQUEST['uid']) ? $_REQUEST['uid'] : $error[] = array('操作人ID不能为空');
        $uids=array();
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            //查看这个课程默认班级下的学生
            $TCourseMember = TCourseMember::find()->where(['course_id'=>$courseId,'class_id'=> \app\models\TBaseClass::MO_REN_ClASS,'del_flag'=>0])->asArray()->all();
            $defaultClassUser = [];
            foreach ($TCourseMember as $value) {
                $defaultClassUser[$value['user_id']] = $value['user_id'];
            }
            $classMember = TBaseClassMember::find()->where(['status' => 'classMember.regulars', 'del_flag' => 0,'class_id'=>explode(',', $classId)])->asArray()->all();
            $insert_data = '';
            $create_time = date("Y-m-d H:i:s");
            
            $error_uid = $exist_uid = [];
            foreach ($classMember as $value) {
                $user_id = $value['user_id'];
                $class_id = $value['class_id'];
                //默认班级中的学生在正常班级中，将学生在默认班级中删除
                if(in_array($user_id, $defaultClassUser)){
                    TCourseMember::updateAll(['del_flag'=>1],['course_id'=>$courseId,'class_id'=> \app\models\TBaseClass::MO_REN_ClASS,'del_flag'=>0,'user_id'=>$user_id]);
                }
                $course_member = TCourseMember::find()->where(['user_id'=>$user_id,'course_id'=>$courseId,'del_flag'=>0])->asArray()->one();
                if(empty($course_member)){
                    $id = Uuid::uuid();
                    $TCourseMember = new TCourseMember();
                    $TCourseMember->id = $id;
                    $TCourseMember->user_id = $user_id;
                    $TCourseMember->class_id = $class_id;
                    $TCourseMember->course_id = $courseId;//开课id
                    $TCourseMember->create_by = $uid;
                    $TCourseMember->create_time = $create_time;
                    $TCourseMember->old_id = $id;
                    $TCourseMember->del_flag = 0;
                    if(!$TCourseMember->save()){
                        $error_uid[] = $user_id;
                    } else {
                        $uids[]=$user_id;
                    }
//                    $insert_data .= "('$id','$user_id','$courseId' ,'$class_id','$uid','$create_time',0,'$id'),";
                } else {
                    $exist_uid[] = $user_id;
                }
            }
            if(!empty($uids)){
                if(empty($error_uid)&&empty($exist_uid)){
                    $result = [
                        'msg' => '操作成功',
                        // 'ver' => $_REQUEST['ver'],
                        'data' => array('studentIds'=>$uids,'exist_uid'=>$exist_uid,'error_uid'=>$error_uid),
                        'success' => true,
                        'code' => '200'
                    ];
                } else {
                    $error_message = $exist_message ='';
                    if(!empty($error_uid)){
                        $error_user = \app\models\TBaseUserProfile::find()->where(['user_id'=>$error_uid])->select('pet_name')->column();
                        $error_message = implode(',', $error_user).'导入课程失败';
                    }
                    if(!empty($exist_uid)){
                        $sql = "SELECT tbup.pet_name,tbc.class_name from t_course_member tcm LEFT JOIN t_base_class tbc on tcm.class_id = tbc.id LEFT JOIN t_base_user_profile tbup on tcm.user_id = tbup.user_id where tcm.course_id = :course_id and tcm.user_id in ('".implode("','", $exist_uid)."') and tcm.del_flag=0";
                        $userMember = TCourseMember::findBySql($sql,[':course_id'=>$courseId])->asArray()->all();
                        foreach ($userMember as $value) {
                            $exist_message.=$value['pet_name'].'已在“'. \yii\helpers\Html::encode($value['class_name']).'”中,';
                        }
                    }
                    $message = trim($error_message.','.$exist_message,',');
                    $result = [
                        'msg' => $message,
                        // 'ver' => $_REQUEST['ver'],
                        'data' => array('studentIds'=>$uids,'exist_uid'=>$exist_uid,'error_uid'=>$error_uid),
                        'success' => true,
                        'code' => '202'
                    ];
                }
                
//                $result = [
//                        'msg' => '操作成功',
//                        // 'ver' => $_REQUEST['ver'],
//                        'data' => array('studentIds'=>$uids,'exist_uid'=>$exist_uid,'error_uid'=>$error_uid),
//                        'success' => true,
//                        'code' => '200'
//                    ];
            } else {
                $result = [
                        'msg' => '此班级的人员已在当前课程的班级中，不可重复导入',
                        'data' => array(),
                        'code' => '201'
                    ];
            }
//            if(!empty($insert_data)){
//                $sql = "INSERT INTO t_course_member (id,user_id,course_id,class_id,create_by,create_time,del_flag,old_id) values" . rtrim($insert_data, ',');
//                $res = Yii::$app->db->createCommand($sql)
//                        ->execute();
//                if ($res) {
//                    $result = [
//                        'msg' => '操作成功',
//                        // 'ver' => $_REQUEST['ver'],
//                        'data' => array('studentIds'=>$uids),
//                        'success' => true,
//                        'code' => '200'
//                    ];
//                } else {
//                    $result = [
//                        'msg' => '操作失败',
//                        // 'ver' => $_REQUEST['ver'],
//                        'data' => [
//                        ],
//                        'success' => false,
//                        'code' => '400'
//                    ];
//                }
//            } else {
//                $result = [
//                        'msg' => '此班级的人员已在当前课程的班级中，不可重复导入',
//                        'data' => array(),
//                        'code' => '201'
//                    ];
//            }
            
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 获取已结课的列表接口
     * @param int  userId:用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-06-12
     * @author: gaoyj
     */
    public function actionGetFinishCourse() {
        $error = array();
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $criteria = '';
        if (isset($_REQUEST['name'])) {
            $criteria .= " and name like binary '%" . trim($_REQUEST['name']) . "%'";
        }
        if (isset($_REQUEST['course_type'])) {
            $criteria .= " and course_type='" . trim($_REQUEST['course_type']) . "'";
        }
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';
        $pageSize = isset($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '20';
        $limit = " limit " . ($page - 1) * $pageSize . ",$pageSize";
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "SELECT * FROM t_course_info WHERE create_by=" . $userId . " AND del_flag=0" . $criteria . $limit;
            $list = \Yii::$app->db->createCommand($sql)->queryAll();
            if ($list) {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'list' => $list,
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 删除课程章节接口
     * @param int  courseId:课程ID userId:用户ID
     * @param int  itemId:章节ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-06-12
     * @author: gaoyj
     */
    public function actionDeleteTeacherCourseItem() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $itemId = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : $error[] = array('章节ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "SELECT * FROM t_course_item_resource_reference WHERE item_id=" . $itemId . " AND del_flag=0 AND course_id=" . $courseId . "";
            $resources = \Yii::$app->db->createCommand($sql)->queryAll();
            if ($resources) {
                $result = [
                    'msg' => '该章节下有资源，不能删除',
                    'ver' => '1.5.0',
                    'date' => [],
                    'success' => false,
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
            $item_id = TCourseItem::find()->select('template_course_item')->where(['id' => $itemId])->asArray()->one();
            $item = TCourseItem::find()->where(['pid' => $item_id['template_course_item'], 'del_flag' => 0])->asArray()->one();
            if ($item) {
                $result = [
                    'msg' => '此节点下有其它节点，不能删除',
                    'ver' => '1.5.0',
                    'date' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
            $model = TCourseItem::find()->where(['id' => $itemId, 'course_id' => $courseId])->one();
            $model->del_flag = 1;
            $model->update_by = $userId;
            $model->update_time = date("Y-m-d H:i:s", time());
            if ($model->validate() && $model->save()) {
                $result = [
                    'msg' => '删除成功',
                    'ver' => '1.5.0',
                    'date' => [
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '删除失败',
                    'ver' => '1.5.0',
                    'date' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 删除章节资源接口
     * @param int  resourseId:资源ID userId:用户ID
     * @param int  itemId:章节ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-06-12
     * @author: gaoyj
     */
    public function actionChapterDeleteResource() {
        $error = array();
        $resourseId = isset($_REQUEST['resourseId']) ? $_REQUEST['resourseId'] : $error[] = array('资源ID不能为空');
        $itemId = isset($_REQUEST['itemId']) ? $_REQUEST['itemId'] : $error[] = array('章节ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "UPDATE t_course_item_resource_reference SET del_flag=1,update_by=:userId,update_time=:up_time WHERE resourse_id=:resourseId AND item_id=:itemId";
            $params = [':userId' => $userId, 'up_time' => date("Y-m-d H:i:s", time()), 'resourseId' => $resourseId, 'itemId' => $itemId];
            $res = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->execute();
            if ($res) {
                $result = [
                    'msg' => '删除成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '删除失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 章节排序接口
     * @param int  id:当前章节ID targetId:目标ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-06-19
     * @author: gaoyj
     */
    public function actionSortCourseItem() {
        $error = array();
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : $error[] = array('ID不能为空');
        $targetId = isset($_REQUEST['targetId']) ? $_REQUEST['targetId'] : $error[] = array('章节ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $item = CourseItem::findOne($id);
            $sort = $item->sequence;
            $targetItem = CourseItem::findOne($targetId);
            $item->sequence = $targetItem->sequence;
            $targetItem->sequence = $sort;
            if ($item->save() && $targetItem->save()) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 章节下资源排序接口
     * @param int  id:当前资源ID targetId:目标ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-06-19
     * @author: gaoyj
     */
    public function actionSortItemResource() {
        $error = array();
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : $error[] = array('资源ID不能为空');
        $targetId = isset($_REQUEST['targetId']) ? $_REQUEST['targetId'] : $error[] = array('资源ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $resources = BCourseItemResource::findOne($id);
            $sort = $resources->sequence;
            $targetResources = BCourseItemResource::findOne($targetId);
            $resources->sequence = $targetResources->sequence;
            $targetResources->sequence = $sort;
            if ($resources->save() && $targetResources->save()) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }
    /**
     * 教师下的课程模板列表
     * @author: gyq
     * @date: 2018/6/28
     */
    public function actionCourseInfoList() {
        $error = array();
        $user_id = empty($_REQUEST['user_id']) ?$error = array('用户id不能为空'): $_REQUEST['user_id'] ;
        $projectId = empty($_REQUEST['projectId']) ?'': $_REQUEST['projectId'];
        $courseType = isset($_REQUEST['courseType']) ? $_REQUEST['courseType'] : '';
        $courseCheckStatus = isset($_REQUEST['courseCheckStatus']) ? $_REQUEST['courseCheckStatus'] : '';
        $keywords = isset($_REQUEST['keywords']) ? $_REQUEST['keywords'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : $page = 1;
        $pageSize = isset($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : 10;
        $limit = "";
        if(!($page == 1 || empty($page))){
            $limit = " limit " . $pageSize * ($page - 1) . "," . $pageSize;
        }
        if (!empty($error)) {
            $result = array(
                "msg" => "操作失败",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $status_sql = '';
            if (!empty($courseCheckStatus)) {
                if ($courseCheckStatus == 'courseCheckStatus.finish') {
                    $status_sql = " and course_status ='" . trim($courseCheckStatus) . "'";
                } elseif ($courseCheckStatus == 'courseCheckStatus.all') {
                    $status_sql = " and course_status ='courseCheckStatus.checked'";
                }
            }
            $and = '';
//            if(!empty($projectId)){
//                $and = " and info.project_id ='$projectId'";
//            }
            $BExamineCourse = BExamine::find()->where(['t_base_user_id'=>$user_id,'del_flag'=>0])->asArray()->all();
            $BCourseAuthor = BCourseAuthor::find()->where(['t_base_user_id'=>$user_id,'del_flag'=>0])->asArray()->all();
            $BCourseOpencourseteachers = BCourseOpencourseteachers::find()->where(['t_base_user_id'=>$user_id,'del_flag'=>0])->asArray()->all();
            if(empty($BExamineCourse)&&empty($BCourseAuthor)&&empty($BCourseOpencourseteachers)){
                $num = 0;
                $info = [];
            } else {
                $bcourseInfo = [];
                foreach ($BCourseAuthor as $value) {
                    $bcourseInfo[$value['t_course_info_id']] = $value['t_course_info_id'];
                }
                foreach ($BExamineCourse as $value) {
                    $bcourseInfo[$value['t_course_info_id']] = $value['t_course_info_id'];
                }
                foreach ($BCourseOpencourseteachers as $value) {
                    $bcourseInfo[$value['t_course_info_id']] = $value['t_course_info_id'];
                }
                $bcourseInfoStr = '';
                if(!empty($bcourseInfo)){
                    $bcourseInfoStr = "'".implode("','", $bcourseInfo)."'";
                }
                if(!empty($bcourseInfoStr)){
                    $sql = "select id,name,course_type,course_status,image_url,image,major_id,major_name,create_by,create_time,group_id from b_course_info "
                        . " where id in ($bcourseInfoStr) $status_sql"
                        . "$and and del_flag=0 ";
                }
                if (!empty($courseType)) {
                    $sql .= " and course_type='" . trim($courseType) . "'";
                } 
                if (!empty($keywords)) {
                    $sql .= " and name like '%" . trim($keywords) . "%'";
                }
                $res = Yii::$app->db->createCommand($sql)->queryAll();
                $num = count($res);
                $sql .= " order by create_time desc ";
                $sql .= $limit;
                $info = Yii::$app->db->createCommand($sql)->queryAll();
                foreach ($info as $key => &$value) {
                    $sql="select count(*) as opencourseNum from t_course_info where del_flag=0 and b_course_info_id=:courseId";
                    $value['num']=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$value['id']])->queryScalar();
                }
            }
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => ['list' => $info, 'num' => $num],
                'code' => '200'
            );
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * 获取所有课程
     */
    public function actionGetCourseList() {
        $error = array();
        $course_id = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error = array('课程id不能为空');
        $search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : '';
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
        } else {
            $courseList = [];
            if(!empty($search)){
                $sql = "SELECT * FROM `b_course_info` WHERE id!='$course_id' and del_flag=0 and course_status='courseCheckStatus.checked' and name like '%$search%' and project_id ='$projectId'  ORDER BY create_time asc; ";
                $courseList = BCourseInfo::findBySql($sql)->asArray()->all();
            } else {
                $courseList = BCourseInfo::find()->where(['del_flag' => 0,'course_status'=>'courseCheckStatus.checked','project_id'=>$projectId])->andWhere(['<>', 'id', $course_id])->orderBy(['create_time'=>SORT_ASC])->asArray()->all();
            }
            if (!empty($courseList)) {
                foreach ($courseList as &$value) {
                    $chapter = BCourseItem::find()->where(['course_id' => $value['id'], 'del_flag' => 0, 'pid' => '0'])->orderBy(['sequence'=>SORT_ASC])->asArray()->all();
                    if (!empty($chapter)) {
                        foreach ($chapter as &$val) {
                            $item = BCourseItem::find()->where(['course_id' => $value['id'], 'del_flag' => 0, 'pid' => $val['id']])->orderBy(['sequence'=>SORT_ASC])->asArray()->all();
                            $val['item'] = $item;
                        }
                    }
                    $value['chapter'] = $chapter;
                }
            }
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => $courseList,
                'code' => '200'
            );
        }

        Yii::$app->end(json_encode($result));
    }

    public function actionGetItems() {
        $error = array();
        $course_id = empty($_REQUEST['course_id']) ? $error = array('课程id不能为空') : $_REQUEST['course_id'];
        if (!empty($error)) {
            $result = array(
                "msg" => "操作失败",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $chapter = BCourseItem::find()->where(['course_id' => $course_id, 'del_flag' => 0, 'pid' => '0'])->asArray()->all();
            if (!empty($chapter)) {
                foreach ($chapter as &$value) {
                    $item = BCourseItem::find()->where(['course_id' => $course_id, 'del_flag' => 0, 'pid' => $value['id']])->asArray()->all();
                    $value['item'] = $item;
                }
            }
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => $chapter,
                'code' => '200'
            );
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 课程模板下的所有章列表
     * User：zyd
     * data:2018/6/26
     */
    public function actionCourseItemList() {
        $error = array();
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "操作失败",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "select * from b_course_item where course_id='" . $course_id . "' and type='courseItemType.unit' and del_flag=0";
            $info = Yii::$app->db->createCommand($sql)->queryAll();
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => $info,
                'code' => '200'
            );
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * 课程模板下的所有章列表
     * User：zyd
     * data:2018/6/26
     */
    public function actionCourseChapterList() {
        $error = array();
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        $unit_id = isset($_REQUEST['unit_id']) ? $_REQUEST['unit_id'] : $error = array('章id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "select t.id,t.pid,t.title,t.content,t.state,t.is_public,rf.name,rf.uri,rf.mime,rf.size,rf.status as file_status,rf.type from b_course_item t "
                    . "left join b_course_item_resource_reference tr on tr.item_top_id=t.id "
                    . "left join t_resource_info r on r.id=tr.resourse_id "
                    . "left join t_resource_file rf on rf.id=r.file_id "
                    . "where t.course_id='" . $course_id . "' and t.pid='" . $unit_id . "' and t.type='courseItemType.chapter' and t.del_flag=0 and tr.del_flag=0 and r.del_flag=0 and rf.del_flag=0 order by t.sequence";
            $info = Yii::$app->db->createCommand($sql)->queryAll();
            foreach ($info as $val) {
                $item_sql = "select t.id,t.pid,t.title,t.content,t.status,t.is_public,rf.name,rf.url,rf.mime,rf.size,rf.status as file_status,rf.type from b_course_item t "
                        . "left join b_course_item_resource_reference tr.item_top_id=t.id "
                        . "left join t_resource_info r on r.id=tr.resourse_id "
                        . "left join t_resource_file rf on rf.id=r.file_id "
                        . "where t.course_id='" . $course_id . "' and t.pid='" . $val['id'] . "' and t.del_flag=0 and tr.del_flag=0 and r.del_flag=0 and rf.del_flag=0 order by t.sequence";
                $item = \Yii::$app->db->createCommand($sql)->queryAll();
                $info[] = array_merge($val, $item);
            }
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => $info,
                'code' => '200'
            );
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * 课程详情
     * User：gyq
     * data:2018/7/5
     */
    public function actionCourseDetails() {
        $error = array();
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            //课程基本信息
            $sql = "select * from b_course_info where id='".$course_id."'";
            $courseinfo = Yii::$app->db->createCommand($sql)->queryOne();
            //建课教师
            $sql = 'SELECT p.pet_name,p.user_id,p.url_image,p.student_no,p.mobilephone,u.username,m.name as major_name FROM t_base_user_profile p 
                    left join t_base_user u on p.user_id=u.id 
                    left join t_base_major_directory m on m.uuid=p.major_id 
                WHERE p.user_id IN (';

            $where1 = "SELECT a.t_base_user_id FROM b_course_author a WHERE a.t_course_info_id = '". $course_id ."' and a.del_flag=0 AND a.is_creater = 1) and  u.del_flag=0 group by p.user_id";
            $sql1 = $sql . $where1;
            $createdCourseTeacher = Yii::$app->db->createCommand($sql1)->queryOne();
            //编课教师
            $where2 = "SELECT a.t_base_user_id FROM b_course_author a WHERE a.t_course_info_id = '" . $course_id . "' and a.del_flag=0 AND a.is_creater = 0) and  u.del_flag=0 group by p.user_id order by pet_name";
            $sql2 = $sql . $where2;
            $editCourseTeacher = Yii::$app->db->createCommand($sql2)->queryAll();
            //审核教师
            $where3 = "SELECT a.t_base_user_id FROM b_examine a WHERE a.t_course_info_id = '" . $course_id . "' and a.del_flag=0) and  u.del_flag=0 group by p.user_id order by pet_name";
            $sql3 = $sql . $where3;
            $reviewCourseTeacher = Yii::$app->db->createCommand($sql3)->queryAll();
            $info = array();
            $info['coursebaseinfo'] = $courseinfo;
            $info['createdcourseteacher'] = $createdCourseTeacher;
            $info['editcourseteacher'] = $editCourseTeacher;
            $info['reviewCourseTeacher'] = $reviewCourseTeacher;
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => ['list' => $info],
                'code' => '200'
            );
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * 组课教师团队删除组课教师
     * User：gyq
     * data:2018/7/5
     */
    public function actionDeleteEditTeacher() {
        $error = array();
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        $author_id = isset($_REQUEST['author_id']) ? $_REQUEST['author_id'] : $error = array('删除教师id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            //课程基本信息
            $update_time = date("Y-m-d H:i:s", time());
            $sql = "UPDATE b_course_author
SET del_flag = 1,update_time=:update_time
WHERE
    t_base_user_id in (" . $author_id . ")
AND t_course_info_id =:t_course_info_id AND is_creater=0";
            $res = Yii::$app->db->createCommand($sql)->bindValues([':update_time'=>$update_time,':t_course_info_id'=>$course_id])->execute();
            //所删除教师的old_id
            $sql="select old_id from t_base_user where del_flag=0 and id in (".$author_id.")";
            $delete_teacher_ids=\yii::$app->db->createCommand($sql)->queryColumn();
            if ($res) {
                $result = array(
                    "msg" => "删除成功",
                    "ver" => "1.5.0",
                    'data' => ['update_time'=>$update_time,'old_id'=>$delete_teacher_ids],
                    'code' => '200'
                );
            } else {
                $result = array(
                    "msg" => "删除失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * 组课教师团队删除审核教师
     * User：gyq
     * data:2018/8/16
     */
    public function actionDeleteReviewTeacher() {
        $error = array();
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        $author_id = isset($_REQUEST['author_id']) ? $_REQUEST['author_id'] : $error = array('删除教师id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            //课程基本信息
            $update_time = date("Y-m-d H:i:s", time());
            $sql = "UPDATE b_examine
SET del_flag = 1,update_time='" . $update_time . "'
WHERE
    t_base_user_id in (" . $author_id . ")
AND t_course_info_id = '" . $course_id."'";
            $res = Yii::$app->db->createCommand($sql)->execute();
            if ($res) {
                $result = array(
                    "msg" => "删除成功",
                    "ver" => "1.5.0",
                    'data' => ['update_time'=>$update_time],
                    'code' => '200'
                );
            } else {
                $result = array(
                    "msg" => "删除失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * 开课详情删除编课教师
     * User：gyq
     * data:2018/7/5
     */
    public function actionOpenCourseDeleteTeacher() {
        $error = array();
        $tcourseId = isset($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error = array('课程模板id不能为空');
        $author_id = isset($_REQUEST['author_id']) ? $_REQUEST['author_id'] : $error = array('删除教师id不能为空');
        $uid = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error = array('uid不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            //课程基本信息
            $update_time = date("Y-m-d H:i:s", time());
            $sql = "UPDATE t_course_teacher
SET del_flag = 1,update_time='" . $update_time . "'
WHERE
    teacher_id in (" . $author_id . ")
AND course_id = '" . $tcourseId . "'";
            $res = Yii::$app->db->createCommand($sql)->execute();
            if ($res) {
                $result = array(
                    "msg" => "删除成功",
                    "ver" => "1.5.0",
                    'data' => ['update_time'=>$update_time],
                    'code' => '200'
                );
            } else {
                $result = array(
                    "msg" => "删除失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /*
     * 组课教师团队添加组课教师
     */

    public function actionAddAuthor() {
        $errors = array();
        $course = !empty($_POST['course_id']) ? $_POST['course_id'] : $errors[] = "课程id不能为空";
        $author = !empty($_POST['author_id']) ? $_POST['author_id'] : $errors[] = "审核教师id不能为空";
        $uid = !empty($_POST['uid']) ? $_POST['uid'] : $errors[] = "uid不能为空";
        if (!empty($errors)) {
            $result = array(
                "msg" => "缺少参数",
                "ver" => "1.5.0",
                'data' => $errors,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $author_arr = explode(',', $author);
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                $create_time=date('Y-m-d H:i:s', time());
                foreach ($author_arr as $key => $value) {
                    //判断教师是否已加入该课程
                    $sql="select * from b_course_author where del_flag=0 and t_course_info_id=:courseId and t_base_user_id=:user_id";
                    $res=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course,':user_id'=>$value])->queryAll();
                    if(!empty($res)){
                        continue;
                    }
                    $id=Uuid::uuid();
                    $sql = "INSERT INTO b_course_author (
                                id,
                                t_course_info_id,
                                t_base_user_id,
                                is_creater,
                                px,
                                create_by,
                                create_time,
                                del_flag
                            )
                                VALUES
                            (
                                '".$id."',
                                '".$course."',
                                '".$value."',
                                0,
                                0,
                                '".$uid."',
                                '" .$create_time. "',
                                0
                            )";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res) {
                        $flag = 1;
                    }
                }
            } catch (Exception $e) {
                $result = array(
                    "msg" => "添加失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '401'
                );
                Yii::$app->end(json_encode($result));
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = array(
                    "msg" => "添加成功",
                    "ver" => "1.5.0",
                    'data' => array('author' => $author,'create_time'=>$create_time),
                    'code' => '200'
                );
            } else {
                $transaction->rollBack();
                $result = array(
                    "msg" => "添加失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /*
     * 组课教师团队添加审核教师
     */

    public function actionAddReviewteachers() {
        $errors = array();
        $course = !empty($_POST['course_id']) ? $_POST['course_id'] : $errors[] = "课程id不能为空";
        $author = !empty($_POST['author_id']) ? $_POST['author_id'] : $errors[] = "审核教师id不能为空";
        $uid = !empty($_POST['uid']) ? $_POST['uid'] : $errors[] = "uid不能为空";
        if (!empty($errors)) {
            $result = array(
                "msg" => "缺少参数",
                "ver" => "1.5.0",
                'data' => $errors,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $author_arr = explode(',', $author);
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                $create_time=date('Y-m-d H:i:s',time());
                foreach ($author_arr as $key => $value) {
                    //判断教师是否已加入该课程
                    $sql="select * from b_examine where del_flag=0 and t_course_info_id=:courseId and t_base_user_id=:user_id";
                    $res=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course,':user_id'=>$value])->queryAll();
                    if(!empty($res)){
                        continue;
                    }
                    $id=Uuid::uuid();
                    $sql = "INSERT INTO b_examine (
                                id,
                                t_course_info_id,
                                t_base_user_id,
                                px,
                                create_by,
                                create_time,
                                del_flag
                            )
                            VALUES(
                                '".$id."',
                                '".$course."',
                                '".$value."',
                               0,
                                '".$uid."',
                                '" .$create_time. "',
                                0
                            )";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res) {
                        $flag = 1;
                    }
                }
            } catch (Exception $e) {
                $result = array(
                    "msg" => "添加失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '401'
                );
                Yii::$app->end(json_encode($result));
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = array(
                    "msg" => "添加成功",
                    "ver" => "1.5.0",
                    'data' => array('author' => $author,'create_time'=>$create_time),
                    'code' => '200'
                );
            } else {
                $transaction->rollBack();
                $result = array(
                    "msg" => "添加失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /*
     * 开课添加主讲教师
     */
    public function actionOpenCourseAddSpeaker() {
        $course = isset($_POST['course_id']) ? $_POST['course_id'] : '';
        $author = isset($_POST['author_id']) ? $_POST['author_id'] : '';
        $uid = isset($_POST['uid']) ? $_POST['uid'] : '';
        if (!empty($author)) {
            //字符串改为数组
            $author = explode(",", $author);
        }
        $transaction = Yii::$app->db->beginTransaction();
        $flag = 0;
        try {
            $sql = "select  create_time from t_course_info where id='" . $course . "' and create_by='" . $uid."'";
            $res = Yii::$app->db->createCommand($sql)->queryOne();
            if (!$res) {
                $flag = 1;
            }
            $create_time =date('Y-m-d H:i:s',time());
            foreach ($author as $k => $v) {
                $sql="select * from t_course_teacher where del_flag=0 and course_id=:courseId and teacher_id=:teacher_id";
                $res=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course,':teacher_id'=>str_replace("'","",$v)])->queryOne();//$v需要去除单引号
                if(empty($res)){
                    $id=Uuid::uuid();
                    $sql = "insert into t_course_teacher (id,course_id,type,teacher_id,create_by,create_time,update_by,update_time,del_flag) values ('".$id."','".$course."','yesOrNo.yes',".$v.",'".$uid."','$create_time','".$uid."','".$create_time."',0)";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res) {
                        $flag = 1;
                    }
                }
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = array(
                    "msg" => "添加成功",
                    "ver" => "1.5.0",
                    'data' => array('author' => $author,'create_time'=>$create_time),
                    'code' => '200'
                );
            } else {
                $transaction->rollBack();
                $result = array(
                    "msg" => "添加失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        } catch (Exception $e) {
            $result = [
                'msg' => '保存失败',
                'ver' => '1.5.0',
                'code' => '500'
            ];
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }
    /*
     * 开课添加辅助教师
     */

    public function actionOpenCourseAddAuthor() {
        $course = isset($_POST['course_id']) ? $_POST['course_id'] : '';
        $author = isset($_POST['author_id']) ? $_POST['author_id'] : '';
        $uid = isset($_POST['uid']) ? $_POST['uid'] : '';
        if (!empty($author)) {
            //字符串改为数组
            $author = explode(",", $author);
        }
        $transaction = Yii::$app->db->beginTransaction();
        $flag = 0;
        try {
            // $sql = "select  create_time from t_course_info where id='" . $course . "' and create_by='" . $uid."'";
            // $res = Yii::$app->db->createCommand($sql)->queryOne();
            // if (!$res) {
            //     $flag = 1;
            // }
            $create_time =date('Y-m-d H:i:s',time());
            foreach ($author as $k => $v) {
                $sql="select * from t_course_teacher where del_flag=0 and course_id=:courseId and teacher_id=:teacher_id";
                $res=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course,':teacher_id'=>str_replace("'","",$v)])->queryOne();//$v需要去除单引号
                if(empty($res)){
                    $id=Uuid::uuid();
                    $sql = "insert into t_course_teacher (id,course_id,type,teacher_id,create_by,create_time,update_by,update_time,del_flag) values ('".$id."','".$course."','yesOrNo.no',".$v.",'".$uid."','$create_time','".$uid."','".$create_time."',0)";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if (!$res) {
                        $flag = 1;
                    }
                }
            }
            if ($flag == 0) {
                $transaction->commit();
                $result = array(
                    "msg" => "添加成功",
                    "ver" => "1.5.0",
                    'data' => array('author' => $author,'create_time'=>$create_time),
                    'code' => '200'
                );
            } else {
                $transaction->rollBack();
                $result = array(
                    "msg" => "添加失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        } catch (Exception $e) {
            $result = [
                'msg' => '保存失败',
                'ver' => '1.5.0',
                'code' => '500'
            ];
            Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 课程模板保存课程详情
     * User：gyq
     * data:2018/7/6
     */
    public function actionSaveDetails() {
        $error = array();
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error = array('用户id不能为空');
        $course_name = isset($_REQUEST['course_name']) ? $_REQUEST['course_name'] : '';
        $image_url = isset($_REQUEST['image_url']) ? $_REQUEST['image_url'] : '';
        $major_name = isset($_REQUEST['major_name']) ? $_REQUEST['major_name'] : '';
        $course_type = isset($_REQUEST['course_type']) ? $_REQUEST['course_type'] : '';
        $group_id = isset($_REQUEST['group_id']) ? $_REQUEST['group_id'] : '';
        $course_lang = isset($_REQUEST['course_lang']) ? $_REQUEST['course_lang'] : 'courseLanguage.chinese';
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : '';
        $study_plan = isset($_REQUEST['study_plan']) ? $_REQUEST['study_plan'] : '';
        $study_require = isset($_REQUEST['study_require']) ? $_REQUEST['study_require'] : '';
        $exam_plan = isset($_REQUEST['exam_plan']) ? $_REQUEST['exam_plan'] : '';
        $is_examine = isset($_REQUEST['is_examine']) ? $_REQUEST['is_examine'] : 0;
        $total_hour = isset($_REQUEST['total_hour']) ? $_REQUEST['total_hour'] : 0;
        $courseVisibility= isset($_REQUEST['courseVisibility']) ? $_REQUEST['courseVisibility'] : '是';
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            //修改课程基本信息
            $update_time = date("Y-m-d H:i:s", time());
            $sql = "UPDATE b_course_info
SET course_type =:course_type
, name =:course_name
, content =:content
, study_plan =:study_plan
, study_require =:study_require
, exam_plan =:exam_plan
, major_name =:major_name
, image_url =:image_url
, group_id =:group_id
, is_examine =:is_examine
, update_time=:update_time
, update_by=:update_by
, total_hour=:total_hour
, course_lang=:course_lang
, course_visibility=:course_visibility
WHERE
    id =:courseId
AND del_flag = 0";
            $res = Yii::$app->db->createCommand($sql)->bindValues([
                ':course_type'=>$course_type,
                ':course_name'=>$course_name,
                ':course_lang'=>$course_lang,
                ':content'=>$content,
                ':study_plan'=>$study_plan,
                ':study_require'=>$study_require,
                ':exam_plan'=>$exam_plan,
                ':major_name'=>$major_name,
                ':image_url'=>$image_url,
                ':group_id'=>$group_id,
                ':is_examine'=>$is_examine,
                ':total_hour'=>$total_hour,
                ':update_time'=>$update_time,
                ':update_by'=>$user_id,
                ':courseId'=>$course_id,
                ':course_visibility'=>$courseVisibility
            ])->execute();
            $sql="select create_time from b_course_info where id='".$course_id."' and del_flag=0";
            $res = Yii::$app->db->createCommand($sql)->queryColumn();
            if ($res) {
                $result = array(
                    "msg" => "修改成功",
                    "ver" => "1.5.0",
                    'data' => ['update_time'=>$update_time,'create_time'=>$res[0]],
                    'code' => '200'
                );
            } else {
                $result = array(
                    "msg" => "修改失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * 开课保存课程详情
     * User：gyq
     * data:2018/7/6
     */
    public function actionOpenCourseSaveDetails() {
        $error = array();
        $tcourseId = isset($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error = array('开课课程id不能为空');
        $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error = array('用户id不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error = array('projectId不能为空');
        $course_name = isset($_REQUEST['course_name']) ? $_REQUEST['course_name'] : '';
        $image_url = isset($_REQUEST['image_url']) ? $_REQUEST['image_url'] : '';
        $stamp_url = isset($_REQUEST['stamp_url']) ? $_REQUEST['stamp_url'] : '';
        $major_name = isset($_REQUEST['major_name']) ? $_REQUEST['major_name'] : '';
//        $school_id = isset($_REQUEST['school_id']) ? $_REQUEST['school_id'] : '';
//        $school_name = isset($_REQUEST['school_name']) ? $_REQUEST['school_name'] : '';
        $course_type = isset($_REQUEST['course_type']) ? $_REQUEST['course_type'] : '';
        $course_lang = isset($_REQUEST['course_lang']) ? $_REQUEST['course_lang'] : 'courseLanguage.chinese';
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : '';
        $study_plan = isset($_REQUEST['study_plan']) ? $_REQUEST['study_plan'] : '';
        $study_require = isset($_REQUEST['study_require']) ? $_REQUEST['study_require'] : '';
        $exam_plan = isset($_REQUEST['exam_plan']) ? $_REQUEST['exam_plan'] : '';
//        $course_tier = isset($_REQUEST['course_tier'])?$_REQUEST['course_tier']:0;
        $location = isset($_REQUEST['location']) ? $_REQUEST['location'] : '';
        $group_id = isset($_REQUEST['group_id']) ? $_REQUEST['group_id'] : '';
        $total_hour = isset($_REQUEST['total_hour']) ? $_REQUEST['total_hour'] : 0;
        $allowed_join = isset($_REQUEST['allowed_join']) ? $_REQUEST['allowed_join'] : 0;
        $course_visibility = isset($_REQUEST['course_visibility']) ? $_REQUEST['course_visibility'] : 'courseVisibility.public';
        $study_progress_weight = isset($_REQUEST['study_progress_weight']) ? $_REQUEST['study_progress_weight'] : 0;
        $study_progress_get_score = isset($_REQUEST['study_progress_get_score']) ? $_REQUEST['study_progress_get_score'] : 0;
        $task_weight = isset($_REQUEST['task_weight']) ? $_REQUEST['task_weight'] : 0;
        $test_weight = isset($_REQUEST['test_weight']) ? $_REQUEST['test_weight'] : 0;
        $talk_weight = isset($_REQUEST['talk_weight']) ? $_REQUEST['talk_weight'] : 0;
        $reply_score = isset($_REQUEST['reply_score']) ? $_REQUEST['reply_score'] : 0;
        $concern_score = isset($_REQUEST['concern_score']) ? $_REQUEST['concern_score'] : 0;
        $pass_line = isset($_REQUEST['pass_line']) ? $_REQUEST['pass_line'] : 0;
        $sign_weight = isset($_REQUEST['sign_weight']) ? $_REQUEST['sign_weight'] : 0;
        $examination = isset($_REQUEST['examination']) ? $_REQUEST['examination'] : 0;
        $visited = isset($_REQUEST['visited']) ? $_REQUEST['visited'] : 0;
        $visited_num = isset($_REQUEST['visited_num']) ? $_REQUEST['visited_num'] : 0;
        $other_weight = isset($_REQUEST['other_weight']) ? $_REQUEST['other_weight'] : 0;
        $course_cycle = empty($_REQUEST['course_cycle']) ? '' : $_REQUEST['course_cycle'];
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try {
                //修改课程基本信息
                $update_time = date("Y-m-d H:i:s", time());
                $sql = "UPDATE t_course_info
SET course_type =:course_type
, name =:course_name
, content =:content
, study_plan =:study_plan
, study_require =:study_require
, exam_plan =:exam_plan
, major_name =:major_name
, image_url =:image_url
, group_id =:group_id
, stamp_url =:stamp_url
, total_hour =:total_hour
, location =:location
, update_time=:update_time
, allowed_join=:allowed_join
, course_visibility=:course_visibility
, course_lang=:course_lang
, course_cycle=:course_cycle
WHERE
    id =:tcourseId
AND del_flag = 0";
                $res = Yii::$app->db->createCommand($sql)->bindValues([
                    ':course_type'=>$course_type,
                    ':course_name'=>$course_name,
                    ':content'=>$content,
                    ':study_plan'=>$study_plan,
                    ':study_require'=>$study_require,
                    ':exam_plan'=>$exam_plan,
                    ':major_name'=>$major_name,
                    ':image_url'=>$image_url,
                    ':stamp_url'=>$stamp_url,
                    ':total_hour'=>$total_hour,
                    ':location'=>$location,
                    ':group_id'=>$group_id,
                    ':update_time'=>$update_time,
                    ':allowed_join'=>$allowed_join,
                    ':course_visibility'=>$course_visibility,
                    ':course_lang'=>$course_lang,
                    ':tcourseId'=>$tcourseId,
//                    ':school_name'=>$school_name,
                    ':course_cycle'=>$course_cycle,
//                    ':school_id'=>$school_id
                ])->execute();
                if (!$res) {
                    $flag = 1;
                }
                $create_time= date("Y-m-d H:i:s", time());
                //处理权重数据(存在更新，不存在插入)
                $sql="select * from t_course_score_weight where del_flag=0 and course_id=:course_id";
                $t_course_score_weight=\yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$tcourseId])->queryOne();
                if(!empty($t_course_score_weight)){
                    //更新权重时修改该课程下其学生分数
                        if($t_course_score_weight['other_weight']!=$other_weight){
                            $sql="select * from t_course_student_score where course_id=:course_id and del_flag=0";
                            $scoreInfo=\yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$tcourseId])->queryAll();
                            foreach ($scoreInfo as $k1=>$v1){
                                $new_score=$v1['other_score']*($other_weight/$t_course_score_weight['other_weight']);
                                $sql="update t_course_student_score set update_time=:update_time,update_by=:update_by,other_score=:other_score where course_id=:course_id and del_flag=0 and student_id=:student_id";
                                $res=\yii::$app->db->createCommand($sql)->bindValues([':update_time'=>$create_time,':update_by'=>$user_id,':other_score'=>$new_score,':course_id'=>$tcourseId,':student_id'=>$v1['student_id']])->execute();
                                if(!$res){
                                    $flag=1;
                                }
                            }
                        }
                    $sql="update t_course_score_weight set 
                                                    learning_progress_weight=$study_progress_weight,
                                                    get_score_progress=$study_progress_get_score,
                                                    task_weight=$task_weight,
                                                    test_weight=$test_weight,
                                                    forum_weight=$talk_weight,
                                                    reply_score=$reply_score,
                                                    concern_score=$concern_score,
                                                    pass_line=$pass_line,
                                                    sign_weight=$sign_weight,
                                                    exam_weight=$examination,
                                                    visited_weight=$visited,
                                                    visited_num=$visited_num,
                                                    other_weight=$other_weight,
                                                    update_by='".$user_id."',
                                                    update_time='".$create_time."' 
                                                  where del_flag=0 and course_id=:course_id";
                    $res=\yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$tcourseId])->execute();
                    if(!$res){
                        $flag=1;
                    }
                }else{
                    $id=Uuid::uuid();
                    $sql="INSERT INTO t_course_score_weight (
	id,
	course_id,
	learning_progress_weight,
	get_score_progress,
	task_weight,
	test_weight,
	forum_weight,
	reply_score,
	concern_score,
	sign_weight,
	exam_weight,
	visited_weight,
	visited_num,
	pass_line,
	other_weight,
	create_by,
	create_time,
	del_flag,
	project_id,
        old_id
)
VALUES
	(:id,
	:course_id,
	:learning_progress_weight,
	:get_score_progress,
	:task_weight,
	:test_weight,
	:forum_weight,
	:reply_score,
	:concern_score,
	:sign_weight,
	:examination,
	:visited,
	:visited_num,
	:pass_line,
	:other_weight,
	:create_by,
	:create_time,
	0,
	:project_id,
        :old_id
	)";
                    $res=\yii::$app->db->createCommand($sql)->bindValues([
                        ':id'=>$id,
                        ':course_id'=>$tcourseId,
                        ':learning_progress_weight'=>$study_progress_weight,
                        ':get_score_progress'=>$study_progress_get_score,
                        ':task_weight'=>$task_weight,
                        ':test_weight'=>$test_weight,
                        ':forum_weight'=>$talk_weight,
                        ':reply_score'=>$reply_score,
                        ':concern_score'=>$concern_score,
                        ':sign_weight'=>$sign_weight,
                        ':examination'=>$examination,
                        ':visited'=>$visited,
                        ':visited_num'=>$visited_num,
                        ':pass_line'=>$pass_line,
                        ':other_weight'=>$other_weight,
                        ':create_by'=>$user_id,
                        ':create_time'=>date('Y-m-d H:i:s', time()),
                        ':project_id'=>$projectId,
                        ':old_id'=>$id
                    ])->execute();
                    if(!$res){
                        $flag=1;
                    }
                }

            } catch (Exception $e) {
                $result = array(
                    "msg" => "修改失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
                Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
            }
            if ($flag == 0) {
                $transaction->commit();
                $sql="select * from t_course_info where id='".$tcourseId."' and del_flag=0";
                $res=\yii::$app->db->createCommand($sql)->queryAll();
                $result = array(
                    "msg" => "修改成功",
                    "ver" => "1.5.0",
                    'data' => ['update_time'=>$update_time,'res'=>$res],
                    'code' => '200'
                );
            } else {
                $transaction->rollBack();
                $result = array(
                    "msg" => "修改失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '401'
                );
            }
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    //验证码邀请码唯一性
    public function actionValidateCode() {
        $error = array();
        $course_code = isset($_REQUEST['course_code']) ? $_REQUEST['course_code'] : $error = array('邀请码不能为空');
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程id不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : '';
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            if (empty($type)) {
                //组课校验
                $sql = "select course_code from b_course_info where id=" . $course_id;
                $code = Yii::$app->db->createCommand($sql)->queryOne();
                if ($code['course_code'] != $course_code) {
                    $sql = "select * from b_course_info where course_code='" . $course_code . "'";
                    $res = Yii::$app->db->createCommand($sql)->queryAll();
                    if ($res) {
                        $result = array(
                            "msg" => "邀请码已存在",
                            "ver" => "1.5.0",
                            'data' => [],
                            'code' => '401'
                        );
                    } else {
                        $result = array(
                            "msg" => "邀请码可以使用",
                            "ver" => "1.5.0",
                            'data' => [],
                            'code' => '200'
                        );
                    }
                    Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
                } else {
                    $result = array(
                        "msg" => "邀请码未更改",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '200'
                    );
                    Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
                }
            } else {
                //开课校验
                $sql = "select course_code from t_course_info where id=" . $course_id;
                $code = Yii::$app->db->createCommand($sql)->queryOne();
                if ($code['course_code'] != $course_code) {
                    $sql = "select * from t_course_info where course_code='" . $course_code . "'";
                    $res = Yii::$app->db->createCommand($sql)->queryAll();
                    if ($res) {
                        $result = array(
                            "msg" => "邀请码已存在",
                            "ver" => "1.5.0",
                            'data' => [],
                            'code' => '401'
                        );
                    } else {
                        $result = array(
                            "msg" => "邀请码可以使用",
                            "ver" => "1.5.0",
                            'data' => [],
                            'code' => '200'
                        );
                    }
                    Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
                } else {
                    $result = array(
                        "msg" => "邀请码未更改",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '200'
                    );
                    Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
                }
            }
        }
    }

    /**
     * 教师下的开课课程列表
     * @author: gyq
     * @date: 2018/6/28
     */
    public function actionOpenCourseInfoList() {
        $error = array();
        $user_id = !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error = array('用户id不能为空');
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : '';
        $courseType = !empty($_REQUEST['courseType']) ? $_REQUEST['courseType'] : '';
        $courseCheckStatus = !empty($_REQUEST['courseCheckStatus']) ? $_REQUEST['courseCheckStatus'] : '';
        $keywords = !empty($_REQUEST['keywords']) ? $_REQUEST['keywords'] : '';
        $page = !empty($_REQUEST['page']) ? $_REQUEST['page'] : $page = 1;
        $pageSize = !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : 10;
        $limit = "";
        if(!($page == 1 || empty($page))){
            $limit = " limit " . $pageSize * ($page - 1) . "," . $pageSize;
        }
        if (!empty($error)) {
            $result = array(
                "msg" => "操作失败",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $sql="SELECT
	DISTINCT i.*
FROM
	t_course_info i
LEFT JOIN t_course_teacher t ON i.id = t.course_id
WHERE
	t.teacher_id = '$user_id'
AND t.del_flag = 0
AND i.del_flag=0";
            if (!empty($courseType)) {
                $sql .= " and i.course_type='" . trim($courseType) . "'";
            } elseif (!empty($courseCheckStatus)) {
                if ($courseCheckStatus == 'courseCheckStatus.finish') {
                    $sql .= " and i.course_status ='" . trim($courseCheckStatus) . "'";
                } elseif ($courseCheckStatus == 'courseCheckStatus.all') {
                    $sql .= " and i.course_status in ('courseCheckStatus.release','courseCheckStatus.default')";
                }
            } elseif (!empty($keywords)) {
                $sql .= " and i.name like '%" . trim($keywords) . "%'";
            }
            $sql .= ' order by i.create_time desc';
            $res = Yii::$app->db->createCommand($sql)->queryAll();
            $num = count($res);
            $sql .= $limit;
            $info = Yii::$app->db->createCommand($sql)->queryAll();
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => ['list' => $info, 'num' => $num],
                'code' => '200'
            );
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 
     */
    public function actionGetBcourseInfo() {
        $id = empty($_POST['bcourseId']) ? $error[] = '课程id不能为空' : $_POST['bcourseId'];
        $tcourseId = empty($_POST['tcourseId']) ? '' : $_POST['tcourseId'];
        if (!empty($tcourseId)) {
            $sql = "select "
                    . "id,b_course_info_id,name,content,course_type,short_title,course_code,course_level,study_plan,study_require,exam_plan,image,location, "
                    . "image_url,total_hour,school,school_name,major_id,major_name from t_course_info "
                    . "where id='" . $tcourseId."'";
        } else {
            $sql = "select "
                    . "id as b_course_info_id,name,content,course_type,short_title,course_code,course_level,study_plan,study_require,exam_plan,"
                    . "image_url,total_hour,school,school_name,major_id,major_name from b_course_info "
                    . "where id='" . $id."'";
        }
        $courseInfo = Yii::$app->db->createCommand($sql)->queryOne();
        $result = array(
            "msg" => "查找成功",
            "ver" => "1.5.0",
            'data' => $courseInfo,
            'code' => '200'
        );
        Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
    }

    /**
     * 获取课程单元章节目录
     */
    public function actionGetCourseOutline1() {
        $error = array();
        $course_id = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程模板id不能为空');
        $sql = 'SELECT
    p.pet_name,p.user_id,p.url_image
FROM
    t_base_user_profile p
left join t_base_user u on p.user_id=u.id
WHERE
    p.user_id IN (
        SELECT
            a.t_base_user_id
        FROM
            b_course_author a';
        $where1 = ' WHERE
            a.t_course_info_id = ' . $course_id . ' and a.del_flag=0
        AND a.is_creater = 1
    ) and  u.del_flag=0';
        $sql1 = $sql . $where1;
        $createdCourseTeacher = Yii::$app->db->createCommand($sql1)->queryOne();
    }

    /**
     * 获取课程下的笔记列表
     *
     * @param $course_id
     *   课程nid
     * @return
     *   包含笔记标题和内容的二维数组
     */
    public function actionGetCourseNoteList() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $uid = isset($_REQUEST['uid']) ? $_REQUEST['uid'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';
        $pageSize = empty($_REQUEST['pagesize']) ? 10 : $_REQUEST['pagesize'];
        $output = array();
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            $sql_conut = "select count(id) sum from t_course_note where course_id='" . $courseId . "' and create_by='" . $uid . "' and del_flag=0";
            $count = Yii::$app->db->createCommand($sql_conut)->queryScalar();
            $sql = "select * from t_course_note where course_id='" . $courseId . "' and create_by='" . $uid . "' and del_flag=0 order by create_time desc,update_time desc limit " . $pageSize * ($page - 1) . ",$pageSize";
            $note_res = Yii::$app->db->createCommand($sql)->queryAll();
            foreach ($note_res as $record) {
                $record['content'] = $record['content']; // drupal_substr(strip_tags($record['content']), 0, 50);
                $record['note_files']['image'] = array();
                $record['note_files']['video'] = array();
                $record['note_files']['audio'] = array();
                $record['note_files']['material'] = array();
                // 获取笔记附件
                $noteid = $record['id'];
                $record['create_time'] = $record['create_time'];
                $sql1 = "select * from t_course_note_file where note_id='" . $noteid . "' and del_flag=0 order by create_time desc";
                $note_files = Yii::$app->db->createCommand($sql1)->queryAll();
                foreach ($note_files as $value) {
                    switch ($value['mime']) {
                        case 'application/msword':
                        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                            $type = 'word';
                            break;
                        case 'application/vnd.ms-excel':
                        case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
                            $type = 'excel';
                            break;
                        case 'application/vnd.ms-powerpoint':
                        case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
                            $type = 'ppt';
                            break;
                        case 'application/pdf':
                            $type = 'pdf';
                            break;
                        case 'text/plain':
                            $type = 'txt';
                            break;
                    }
                    // var_dump($value);
                    $file_info = array();
                    // 只显示至多三个图片 && !(count($record['note_files']['image']) > 7)
                    if ($value['mime'] == 'image/jpeg' || $value['mime'] == 'image/png' || $value['mime'] == 'image/*' || $value['mime'] == 'image/gif') {
                        //var_dump( $value['file_uri']);
                        $file_info = array(
//                            'small'=>image_style_url("large", $value['file_uri']),
                            'original' => Yii::$app->params['fileUrl'] . $value['file_uri'],
                            'size' => $value['size'],
                            'fid' => $value['id']
                        );
                        $record['note_files']['image'][] = $file_info;
                    } elseif ($value['mime'] == 'video/mp4' && empty($record['note_files']['video'])) { // 只显示至多一个视频
                        $record['note_files']['video'][] = array('original' => Yii::$app->params['fileUrl'] . $value['file_uri'], 'size' => $value['size'], 'fid' => $value['id']);
                    } elseif ($value['mime'] == 'audio/mpeg' || $value['mime'] == 'audio/mp3') { // 音频3个
                        $record['note_files']['audio'][] = array('filename' => $value['name'], 'original' => Yii::$app->params['fileUrl'] . $value['file_uri'], 'size' => $value['size'], 'fid' => $value['id']);
                    } elseif ($value['mime'] == 'application/msword' || $value['mime'] == 'application/vnd.ms-excel' || $value['mime'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || $value['mime'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || $value['mime'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation' || $value['mime'] == 'application/vnd.ms-powerpoint' || $value['mime'] == 'text/plain' || $value['mime'] == 'application/pdf') { //
//                        if(!empty($enable_third_party_docment_convert)){
                        $html_url = BaseController::getFileHtmlUrl(Yii::$app->params['fileUrl'] . $value['file_uri']);
//                        }else {
//                            $html_url = $value['file_uri'];
//                        }
                        $record['note_files']['material'][] = array('type' => $type, 'filename' => $value['name'], 'original' => $html_url, 'size' => $value['size'], 'fid' => $value['id']);
                    }
                }
                $output[] = $record;
            }
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => [
                    'list' => $output,
                    'sum' => $count,
                ],
                'code' => '200'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }

    public function actionGetCourseNoteShareList() {
        $error = array();
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $uid = isset($_REQUEST['uid']) ? $_REQUEST['uid'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';
        $pageSize = empty($_REQUEST['pagesize']) ? 10 : $_REQUEST['pagesize'];
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            $count = TCourseNote::find()->where(['course_id' => $courseId, 'del_flag' => 0, 'is_share' => 'yesOrNo.yes'])->count();
            $shareNoteList = TCourseNote::findBySql("select * from t_course_note where course_id='" . $courseId . "' and is_share='yesOrNo.yes' and del_flag=0 order by create_time desc,update_time desc limit " . $pageSize * ($page - 1) . ",$pageSize")->asArray()->all();
            //$shareNoteList = TCourseNote::find()->where(['course_id' => $courseId, 'del_flag' => 0, 'is_share' => 'yesOrNo.yes'])->orderBy(['create_time' => SORT_DESC])->asArray()->all();
            foreach ($shareNoteList as &$value) {
                $value['user_info'] = \app\models\User::getUserInfoByUid($value['create_by']);
            }
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => [
                    'sum'=>$count,
                    'list'=>$shareNoteList,
                ],
                'code' => '200'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }

    public function actionGetNoteContent() {
        $error = array();
        $noteId = isset($_REQUEST['note_id']) ? $_REQUEST['note_id'] : $error[] = array('笔记ID不能为空');
        $courseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $output = array();
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            $sql = "select * from t_course_note where id='" . $noteId . "' and course_id='".$courseId."' and del_flag=0";
            $note_res = Yii::$app->db->createCommand($sql)->queryAll();
            foreach ($note_res as $record) {
                $record['content'] = $record['content']; // drupal_substr(strip_tags($record['content']), 0, 50);
                $record['note_files']['image'] = array();
                $record['note_files']['video'] = array();
                $record['note_files']['audio'] = array();
                $record['note_files']['material'] = array();
                // 获取笔记附件
                $noteid = $record['id'];
                $record['create_time'] = $record['create_time'];
                $sql1 = "select * from t_course_note_file where note_id='" . $noteid . "' and del_flag=0 order by create_time desc";
                $note_files = Yii::$app->db->createCommand($sql1)->queryAll();
                foreach ($note_files as $value) {
                    switch ($value['mime']) {
                        case 'application/msword':
                        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                            $type = 'word';
                            break;
                        case 'application/vnd.ms-excel':
                        case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
                            $type = 'excel';
                            break;
                        case 'application/vnd.ms-powerpoint':
                        case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
                            $type = 'ppt';
                            break;
                        case 'application/pdf':
                            $type = 'pdf';
                            break;
                        case 'text/plain':
                            $type = 'txt';
                            break;
                    }
                    // var_dump($value);
                    $file_info = array();
                    // 只显示至多三个图片 && !(count($record['note_files']['image']) > 7)
                    if ($value['mime'] == 'image/jpeg' || $value['mime'] == 'image/png' || $value['mime'] == 'image/*' || $value['mime'] == 'image/gif') {
                        //var_dump( $value['file_uri']);
                        $file_info = array(
//                            'small'=>image_style_url("large", $value['file_uri']),
                            'original' => Yii::$app->params['fileUrl'] . $value['file_uri'],
                            'fid' => $value['id'],
                            'filename' => $value['name'],
                            'size' => $value['size']
                        );
                        $record['note_files']['image'][] = $file_info;
                    } elseif (($value['mime'] == 'application/x-shockwave-flash'||strpos($value['mime'],'video') !== false) && empty($record['note_files']['video'])) { // 只显示至多一个视频
                        $record['note_files']['video'][] = array('original' => Yii::$app->params['fileUrl'] . $value['file_uri'], 'size' => $value['size'], 'fid' => $value['id'], 'filename' => $value['name']);
                    } elseif ($value['mime'] == 'audio/mpeg' || $value['mime'] == 'audio/mp3') { // 音频3个
                        $record['note_files']['audio'][] = array('filename' => $value['name'], 'original' => Yii::$app->params['fileUrl'] . $value['file_uri'], 'size' => $value['size'], 'fid' => $value['id']);
                    } elseif ($value['mime'] == 'application/msword' || $value['mime'] == 'application/vnd.ms-excel' || $value['mime'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || $value['mime'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || $value['mime'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation' || $value['mime'] == 'application/vnd.ms-powerpoint' || $value['mime'] == 'text/plain' || $value['mime'] == 'application/pdf') { //
//                        if(!empty($enable_third_party_docment_convert)){
                        $html_url = BaseController::getFileHtmlUrl(Yii::$app->params['fileUrl'] . $value['file_uri']);
//                        }else {
//                            $html_url = $value['file_uri'];
//                        }
                        $record['note_files']['material'][] = array('type' => $type, 'filename' => $value['name'], 'original' => $html_url, 'size' => $value['size'], 'fid' => $value['id']);
                    }
                }
                $output = $record;
            }
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => $output,
                'code' => '200'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }

    public function actionSaveNote() {
        $error = array();
        $title = isset($_REQUEST['title']) ? $_REQUEST['title'] : $error[] = array('标题不能为空');
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : $error[] = array('内容不能为空');
        $author = isset($_REQUEST['author']) ? $_REQUEST['author'] : $error[] = array('作者不能为空');
        $courseId = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error[] = array('课程ID不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        if (isset($_REQUEST['note_id'])) {// 更新  
            $noteId = $_REQUEST['note_id'];
            $res = \Yii::$app->db->createCommand()->update('t_course_note', ['title' => $title, 'content' => $content, 'update_by' => $author, 'update_time' => date("Y-m-d H:i:s", time())], 'id=:id', [':id' => $noteId])->execute();
            if ($res) {
                if (!empty($_REQUEST['file_id'])) {
                    $fileId = $_REQUEST['file_id'];
                    $noteFile = \app\models\TCourseNoteFile::updateAll(['note_id' => $noteId], ['id' => explode(',', $fileId), 'del_flag' => 0]);
                }
                if (!empty($_REQUEST['delete_fid'])) {
                    $delete_fid = $_REQUEST['delete_fid'];
                    $deleteNoteFile = \app\models\TCourseNoteFile::updateAll(['del_flag' => 1], ['id' => explode(',', $delete_fid), 'del_flag' => 0]);
                }
                $result = array(
                    "msg" => "操作成功",
                    "ver" => "1.5.0",
                    'data' => ['flag' => '1','note_id'=>$noteId],
                    'code' => '200'
                );
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
        } else {
            $create_time = date("Y-m-d H:i:s", time());
            $db = Yii::$app->db;
            $transaction = $db->beginTransaction();
            $TCourseNote = new \app\models\TCourseNote();
            $TCourseNote->id = Uuid::uuid();
            $TCourseNote->title = $title;
            $TCourseNote->content = $content;
            $TCourseNote->create_by = $author;
            $TCourseNote->is_share = "yesOrNo.no";
            $TCourseNote->create_time = $create_time;
            $TCourseNote->course_id = $courseId;
            $res = $TCourseNote->save();
            if ($res) {
                $id = $TCourseNote->attributes['id'];
                $file_up_flag = false;
                if (!empty($_REQUEST['file_id'])) {
                    $file_id = $_REQUEST['file_id']; //
                    $file_id = "'".implode("','",explode(',', trim($file_id,',')))."'";
                    $sql = "update t_course_note_file set note_id = '$id'  where id in (" . $file_id . ")";
                    $file_res = $db->createCommand($sql)->execute();
                    if ($file_res) {
                        $file_up_flag = true;
                    }
                } else {
                    $file_up_flag = true;
                }
                if (!empty($_REQUEST['delete_fid'])) {
                    $delete_fid = $_REQUEST['delete_fid'];
                    $deleteNoteFile = \app\models\TCourseNoteFile::updateAll(['del_flag' => 1], ['id' => explode(',', $delete_fid), 'del_flag' => 0]);
                }
                if ($file_up_flag) {
                    $transaction->commit();
                    $result = array(
                        "msg" => "操作成功",
                        "ver" => "1.5.0",
                        'data' => ['flag' => '1','note_id'=>$TCourseNote->attributes['id'],'create_time'=>$create_time],
                        'code' => '200'
                    );
                    Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
                }
            } else {
                $transaction->rollback(); // 如果操作失败, 数据回滚
                $result = array(
                    "msg" => "操作失败",
                    "ver" => "1.5.0",
                    'data' => ['flag' => '0'],
                    'code' => '400'
                );
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
        }
    }

    /**
     * 删除笔记
     */
    public function actionDeleteNote() {
        $error = array();
        $note_id = !empty($_REQUEST['note_id']) ? $_REQUEST['note_id'] : $error = array('笔记id不能为空');
        $course_id = !empty($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程id不能为空');
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "操作失败",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $res = TCourseNote::updateAll(['del_flag' => 1], ['id' => $note_id, 'course_id' => $course_id, 'del_flag' => 0]);
            if ($res!==false) {
                $res_file = \app\models\TCourseNoteFile::updateAll(['del_flag' => 1], ['note_id' => $note_id, 'del_flag' => 0]);
                if ($res_file!==false) {
                    $transaction->commit();
                    $result = array(
                        "msg" => "删除成功",
                        "ver" => "1.5.0",
                        'data' => array(),
                        'code' => '200'
                    );
                } else {
                    $transaction->rollBack();
                    $result = array(
                        "msg" => "删除失败",
                        "ver" => "1.5.0",
                        'data' => array(),
                        'code' => '401'
                    );
                }
            } else {
                $transaction->rollBack();
                $result = array(
                    "msg" => "删除失败",
                    "ver" => "1.5.0",
                    'data' => array(),
                    'code' => '400'
                );
            }
        }
        Yii::$app->end(json_encode($result));
    }

    /**
     * 分享笔记
     */
    public function actionShareNote() {
        $error = array();
        $note_id = !empty($_REQUEST['note_id']) ? $_REQUEST['note_id'] : $error = array('笔记id不能为空');
        $course_id = !empty($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array('课程id不能为空');
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "操作失败",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
        } else {
            $TCourseNote = TCourseNote::findOne($note_id);
            if($TCourseNote->is_share == 'yesOrNo.no'){
                $res = TCourseNote::updateAll(['is_share' => 'yesOrNo.yes'], ['id' => $note_id, 'course_id' => $course_id, 'del_flag' => 0]);
            } elseif($TCourseNote->is_share == 'yesOrNo.yes') {
                $res = TCourseNote::updateAll(['is_share' => 'yesOrNo.no'], ['id' => $note_id, 'course_id' => $course_id, 'del_flag' => 0]);
            }
            if ($res!==false) {
                $result = array(
                    "msg" => "操作成功",
                    "ver" => "1.5.0",
                    'data' => array(),
                    'code' => '200'
                );
            } else {
                $result = array(
                    "msg" => "操作失败",
                    "ver" => "1.5.0",
                    'data' => array(),
                    'code' => '400'
                );
            }
        }
        Yii::$app->end(json_encode($result));
    }
    /**
     * 获取引用资源的课程信息
     */
    public function actionCourseUseResourceInfo() {
        $error = array();
        $resource_id = isset($_REQUEST['resource_id']) ? $_REQUEST['resource_id'] : $error[] = array('资源id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            $resourceReference = \app\models\TCourseItemResourceReference::find()->where(['resourse_id'=>$resource_id,'del_flag'=>0])->asArray()->all();
            $t_course = [];
            foreach ($resourceReference as $value) {
                $t_course[$value['course_id']] = $value['course_id'];
            }
            $course_str = "'".implode("','", $t_course)."'";
//            $TCourseInfo = TCourseInfo::find()->where(['id'=>$t_course,'del_flag'=>0])->asArray()->all();
                	$sql = "SELECT
                    tci.id,tci.b_course_info_id,tci.name,tci.project_id,tci.major_name,tci.school_name,tci.image_url,UNIX_TIMESTAMP(tci.create_time) AS create_time,p.pet_name
                FROM
                    t_course_info tci
                LEFT JOIN t_base_user_profile p ON p.user_id = tci.create_by
                WHERE tci.id in (".$course_str.")
                AND tci.course_visibility='courseVisibility.public'
                AND tci.del_flag = 0";
                $info = Yii::$app->db->createCommand($sql)->queryAll();
                if($info){
			foreach ($info as &$value)
			{
				$peo_num = TCourseMember::find()->select('user_id')->distinct()->where('course_id=:courseId and del_flag=0',[':courseId' => $value['id']])->count();
				$value['p_num'] = $peo_num;
                $sql1 = "select count(*) as num from t_course_evaluate where del_flag=0 and type='praiseStudentOrTeacher.student' and object_id=:obj and course_id=:courseId";
                $courseEvaluateNum = \yii::$app->db->createCommand($sql1)->bindValue(':courseId',$value['id'])->bindValue(':obj',$value['id'])->queryOne();
                empty($courseEvaluateNum)?$pingnum=0:$pingnum=$courseEvaluateNum['num'];
                $value['courseEvaluateNum'] = $pingnum;
                }
                
                        }
//            $sql = "SELECT t.*
//	from b_course_info t
//WHERE
//	t.id IN (
//		SELECT
//			i.course_id
//		FROM
//			t_course_item i
//		WHERE
//			i.template_course_item IN (
//				SELECT
//					r.item_id
//				FROM
//					t_course_item_resource_reference r
//				WHERE
//					r.resourse_id ='" . $resource_id . "' and r.del_flag=0
//			) and i.del_flag=0
//	) 	and t.del_flag=0 GROUP BY t.id";
//            $res = Yii::$app->db->createCommand($sql)->queryAll();
            $result = array(
                "msg" => "操作成功",
                "ver" => "1.5.0",
                'data' => $info,
                'code' => '200'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }

    /**
     * 我的课程列表接口
     * @param int  userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-06-25
     * @author: gaoyj
     */
    public function actionGetMyCoursePageList() {
        $error = array();
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        $courseType = !empty($_REQUEST['courseType']) ? $_REQUEST['courseType'] : '';
        $courseCheckStatus = !empty($_REQUEST['courseCheckStatus']) ? $_REQUEST['courseCheckStatus'] : '';
        $keywords = !empty($_REQUEST['keywords']) ? $_REQUEST['keywords'] : '';
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "SELECT distinct course_id FROM t_course_member WHERE user_id=:userId AND del_flag=0 ";
            $params = [':userId' => $userId];
            $list = Yii::$app->db->createCommand($sql)
                    ->bindValues($params)
                    ->queryColumn();
            if ($list) {
//                $id = implode(',', $list);
                $id = '"'.implode('","', $list).'"';
            } elseif (empty($list)) {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => array(),
                    'success' => false,
                    'code' => '404'
                ];
                Yii::$app->end(json_encode($result));
            } elseif ($list === false) {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [
                    ],
                    'success' => false,
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
            $where = '';
            if (!empty($courseType)) {
                $where .= " and course_type='" . trim($courseType) . "'";
            }
            if (!empty($courseCheckStatus)) {
                $where .= " and course_status='" . trim($courseCheckStatus) . "'";
            }
            if (!empty($keywords)) {
                $where .= " and name like '%" . trim($keywords) . "%'";
            }
            $sql1 = "SELECT
                        id,project_id,image_url,name,course_type,create_time,b_course_info_id,major_name,course_status,school_name
                    FROM
                        t_course_info tci
                    WHERE
                        id IN (" . $id . ")
                    AND del_flag = 0 
                    " . $where . "
                    GROUP BY
                        id ";
            $res = Yii::$app->db->createCommand($sql1)->queryAll();
            $num = count($res);
            $course = Yii::$app->db->createCommand($sql1)->queryAll();
            if ($course) {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ['list' => $course, 'num' => $num],
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => array(),
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /*
     * 开课 查询课程详情
     * input: tcourseId projectId
     * output json
     * gyq 20180806
     * */

    public function actionOpenCourseGetCourseDetails() {
        $error = array();
        $courseId = !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error = array("开课Id不能为空");
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error = array("项目Id不能为空");
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            //课程基本信息
            $sql = "select * from t_course_info where id=:course_id";
            $courseinfo = Yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$courseId])->queryOne();
            //主讲教师
            $sql = 'SELECT
    p.pet_name,p.user_id,p.url_image,p.student_no,p.mobilephone,u.username,m.name as major_name
FROM
    t_base_user_profile p
left join t_base_user u on p.user_id=u.id
left join t_base_major_directory m on m.uuid=p.major_id
left join t_course_teacher tct on tct.teacher_id=p.user_id
WHERE
    p.user_id IN (
        SELECT
            t.teacher_id
        FROM
            t_course_teacher t';
            $where1 = " WHERE
            t.course_id = '" . $courseId . "' and t.del_flag=0
        AND t.type = 'yesOrNo.yes'
    ) and  u.del_flag=0  and p.type='userType.teacher' and tct.del_flag=0 and tct.course_id='".$courseId."' order by tct.update_time asc";
            $sql1 = $sql . $where1;
            $createdCourseTeacher = Yii::$app->db->createCommand($sql1)->queryAll();
            //辅助教师
            $where2 = " WHERE
            t.course_id = '" . $courseId . "' and t.del_flag=0
        AND t.type = 'yesOrNo.no'
    ) and  u.del_flag=0  and p.type='userType.teacher'  and tct.del_flag=0 and tct.course_id='".$courseId."' order by tct.update_time asc";
            if (!empty($keywords)) {
                $where2 .= " and p.pet_name like '%" . $keywords . "%' ";
            }
            $sql2 = $sql . $where2;
            $assistant = Yii::$app->db->createCommand($sql2)->queryAll();
            $sql = "select * from t_course_score_weight where course_id='" . $courseId . "' and del_flag=0";
            $weight = Yii::$app->db->createCommand($sql)->queryOne();
            $info = array();
            $info['coursebaseinfo'] = $courseinfo;
            $info['createdCourseTeacher'] = $createdCourseTeacher;
            $info['assistant'] = $assistant;
            $info['course_weight'] = $weight;
            //课程下是否有学生已经领取证书
            $sql="select * from t_course_student_credit where del_flag=0 and course_id=:course_id";
            $whetherToReceive=\yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$courseId])->queryAll();
            $receiveFlag=false;
            if(!empty($whetherToReceive)){
                $receiveFlag=true;
            }
            $info['receiveFlag']=$receiveFlag;
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => ['list' => $info],
                'code' => '200'
            );
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /*
     * 获取课程大纲信息(组课)
     * 2018/09/01
     * gyq
     */

    public function actionGetCourseOutlineInfo() {
        $error = array();
        $courseId = !empty($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error = array("课程Id不能为空");
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : '';
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            $sql = "select * from b_course_outline_file where del_flag=0 and course_id=:course_id order by create_time desc limit 1";
            $res = Yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$courseId])->queryOne();
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => $res,
                'code' => '200'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }

    /*
     * 获取课程大纲信息(开课)
     * 2018/09/03
     * gyq
     */

    public function actionGetOpenCourseOutlineInfo() {
        $error = array();
        $courseId = !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error = array("课程Id不能为空");
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error = array("项目Id不能为空");
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            $sql = "select * from t_course_outline_file where del_flag=0 and t_course_id=:t_course_id  order by create_time desc limit 1";
            $res = Yii::$app->db->createCommand($sql)->bindValues([':t_course_id'=>$courseId])->queryOne();
            $result = array(
                "msg" => "查找成功",
                "ver" => "1.5.0",
                'data' => $res,
                'code' => '200'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }

    /*
     * 将模板课课程大纲信息保存到开课课程下
     * 2018/09/03
     * gyq
     */

    public function actionSaveOrganizeCourseOutline() {
        $error = array();
        $tcourseId = !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error = array("开课课程Id不能为空");
        $bcourseId = !empty($_REQUEST['bcourseId']) ? $_REQUEST['bcourseId'] : $error = array("组课课程Id不能为空");
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error = array("项目Id不能为空");
        $userId = !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error = array("用户Id不能为空");
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            $update_time=date('Y-m-d H:i:s', time());
            $sql = "select * from b_course_outline_file where del_flag=0 and course_id='" . $bcourseId . "' order by create_time desc limit 1";
            $courseoutlineinfo = Yii::$app->db->createCommand($sql)->queryOne();
            if ($courseoutlineinfo) {
                $sql = "select * from t_course_outline_file where t_course_id='" . $tcourseId . "' and del_flag=0";
                $res = Yii::$app->db->createCommand($sql)->queryOne();
                if ($res) {
                    $sql = "update t_course_outline_file set update_by='" . $userId . "',update_time='" . $update_time. "' where t_course_id='" . $tcourseId . "' and del_flag=0";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if ($res) {
                        $result = array(
                            "msg" => "更新成功",
                            "ver" => "1.5.0",
                            'data' => $res,
                            'code' => '200'
                        );
                    } else {
                        $result = array(
                            "msg" => "保存成功",
                            "ver" => "1.5.0",
                            'data' => [],
                            'code' => '401'
                        );
                    }
                    Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
                } else {
                    $create_time=date('Y-m-d H:i:s', time());
                    $sql = "insert into t_course_outline_file (id,t_course_id,course_id,content,create_by,create_time,del_flag) values('".Uuid::uuid()."','".$tcourseId."','".$bcourseId."','" . $courseoutlineinfo['content'] . "','" . $userId . "','" . $create_time. "',0)";
                    $res = Yii::$app->db->createCommand($sql)->execute();
                    if ($res) {
                        $result = array(
                            "msg" => "保存成功",
                            "ver" => "1.5.0",
                            'data' => $res,
                            'code' => '200'
                        );
                    } else {
                        $result = array(
                            "msg" => "保存失败",
                            "ver" => "1.5.0",
                            'data' => [],
                            'code' => '400'
                        );
                    }
                    Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
                }
            }
        }
    }

    public function actionDeleteTcourse() {
        $id = !empty($_POST['courseId']) ? $_POST['courseId'] : $error[] = '课程id 不能为空';
        $projectId = !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error = array("项目Id不能为空");
        $userId = !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error = array("用户Id不能为空");
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        $tcourse_id = explode(',', $id);
//        $tcourseRes = TCourseInfo::updateAll(['del_flag'=>1],['id'=>$tcourse_id,'del_flag'=>0]);
        $tcourseRes = TCourseInfo::findOne($tcourse_id);
        $tcourseRes->del_flag=1;
        $tcourseRes->update_by=$userId;
        $tcourseRes->update_time= date('Y-m-d H:i:s');
        if($tcourseRes->validate() && $tcourseRes->save()){
            $result = array(
                    "msg" => "保存成功",
                    "ver" => "1.5.0",
                    'data' => ['bcourseId'=>$tcourseRes->b_course_info_id],
                    'code' => '200'
                );
        } else {
            $result = array(
                    "msg" => "保存失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
        }
        Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
    }
    //提交审核课程
    public function actionReviewCourse() {
        $error = array();
        $courseIds = isset($_REQUEST['courseIds']) ? $_REQUEST['courseIds'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (empty($error)) {
            $update_time=date("Y-m-d H:i:s", time());
                $sql = "UPDATE b_course_info SET course_status='courseCheckStatus.checking',update_by='" . $userId . "',update_time='" . $update_time. "' WHERE id IN(" . $courseIds . ") ";
                $res = \Yii::$app->db->createCommand($sql)->execute();
                if($res){
                    $result = array(
                        "msg" => "更新成功",
                        "ver" => "1.5.0",
                        'data' => ['update_time'=>$update_time],
                        'code' => '200'
                    );
                }else{
                    $result = array(
                        "msg" => "更新失败",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '400'
                    );
                }
                Yii::$app->end(json_encode($result));
        } else {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
    }
    public function actionLeaveCourse() {
        $error = array();
        $courseId = isset($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error[] = array('课程ID不能为空');
        $userId = isset($_REQUEST['uid']) ? $_REQUEST['uid'] : $error[] = array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[] = array('联盟ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                // 'ver' => $_REQUEST['ver'],
                'data' => $error,
                'code' => '601'
            ];    
        } else {
            $TCourseMember = TCourseMember::updateAll(['update_by'=>$userId,'update_time'=> date("Y-m-d H:i:s"),'del_flag'=>1],['user_id'=>$userId,'course_id'=>$courseId,'del_flag'=>0]);
            if($TCourseMember!==false){
                $result = array(
                        "msg" => "操作成功",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '200'
                    );
            }else{
                $result = array(
                    "msg" => "更新失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
        }
        Yii::$app->end(json_encode($result));
    }
    /**
     * 学员列表接口
     * @param int  userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-10-12
     * @author: gaoyj
     */
    public function actionStudentList()
    {
        $error = array();
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $sql = "SELECT
                        a.user_id,tbup.pet_name,tbu.username,ifnull( tbc.class_name, '默认班级' ) AS class_name 
                    FROM
                        t_course_member a
                        LEFT JOIN t_base_device b ON a.user_id = b.user_id
                        LEFT JOIN t_base_user tbu ON b.user_id = tbu.id
                        LEFT JOIN t_base_user_profile tbup ON tbup.user_id = tbu.id
                        LEFT JOIN t_base_class tbc ON a.class_id = tbc.id 
                    WHERE
                        a.course_id =:courseId 
                        AND a.del_flag = 0 
                        AND b.push_token != '' 
                        AND b.del_flag = 0 
                        AND tbu.del_flag = 0 
                        AND tbup.del_flag = 0 
                    GROUP BY
                        a.user_id";
            $params = [':courseId' => $courseId];
            $userInfo = Yii::$app->db->createCommand($sql)
                           ->bindValues($params)
                           ->queryAll();
            if ($userInfo) {
                foreach ($userInfo as $key => $value) {
                    $sql2 = "SELECT push_token FROM t_base_device WHERE user_id='".$value['user_id']."' AND del_flag=0 ORDER BY update_time DESC";
                    $pushToken = Yii::$app->db->createCommand($sql2)->queryOne();
                    $userInfo[$key]['push_token'] = $pushToken['push_token'];
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $userInfo,
                    'success' => true,
                    'code' => '200'
                ];
            // $sql = "SELECT DISTINCT user_id,class_id FROM t_course_member WHERE course_id=:courseId AND del_flag=0";
            // $params = [':courseId' => $courseId];
            // $member = Yii::$app->db->createCommand($sql)
            //                ->bindValues($params)
            //                ->queryAll();
            // if($member)
            // {
            //     $userInfo = [];
            //     foreach ($member as $key => $val)
            //     {
            //         $class_sql = "SELECT class_name FROM t_base_class WHERE id='".$val['class_id']."' AND del_flag=0";
            //         $class_name = Yii::$app->db->createCommand($class_sql)->queryOne();
            //         if($class_name)
            //         {
            //             $member[$key]['class_name'] = $class_name['class_name'];
            //         }
            //         else
            //         {
            //             $member[$key]['class_name'] = '';
            //         }
            //         if($val['class_id']=='-1')
            //         {
            //             $member[$key]['class_name'] = \app\models\TBaseClass::$defalutClass['-1'];
            //         }
            //         $u_sql = "SELECT
            //                     tbup.user_id,tbd.push_token,tbup.pet_name,tbu.username
            //                 FROM
            //                     t_base_device tbd 
            //                 LEFT JOIN t_base_user tbu ON tbd.user_id = tbu.id
            //                 LEFT JOIN t_base_user_profile tbup ON tbup.user_id = tbu.id
            //                 WHERE
            //                     tbd.user_id='".$val['user_id']."' AND tbd.push_token!='' AND tbu.del_flag=0 AND tbup.del_flag=0 ORDER BY UNIX_TIMESTAMP(tbd.update_time) DESC";
            //         $user = Yii::$app->db->createCommand($u_sql)->queryOne();
            //         if($user)
            //         {
            //             $user['class_name'] = $member[$key]['class_name'];
            //             $userInfo[] = $user;
            //         }
            //     }
            }
            elseif(empty($member))
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ];
            }
            elseif($member===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 管理中心的课程模板列表
     * @author: Gyj
     * @date: 2018/11/07
     */
    public function actionGetManageCenterCourse() {
        $error = array();
        $user_id = empty($_REQUEST['userId']) ?$error = array('用户id不能为空'): $_REQUEST['userId'] ;
        $roleType = empty($_REQUEST['roleType']) ?$error = array('角色类型不能为空'): $_REQUEST['roleType'] ;
        $courseCheckStatus = isset($_REQUEST['courseCheckStatus']) ? $_REQUEST['courseCheckStatus'] : '';
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $and = ' and 1=2';
            $sql = "SELECT project_id FROM t_base_user WHERE id='".$user_id."' AND del_flag=0";
            $projectId = Yii::$app->db->createCommand($sql)->queryScalar();
            if($roleType=='projectAdmin'){
                if(!empty($projectId)){
                    $and = " and info.project_id = '".$projectId."'";
                }
            }
            if($roleType=='schoolAdmin'){
                if(!empty($projectId)){
                    $s_sql = "SELECT school_id,major_id FROM t_base_user_profile WHERE user_id='".$user_id."' AND del_flag=0";
                    $school = Yii::$app->db->createCommand($s_sql)->queryOne();
                    $and = " and info.school = '".$school['school_id']."' and info.project_id = '".$projectId."'";
                }
            }
            if($roleType=='systemAdmin'){
                $and = "";
            }
            $status_sql = '';
            if (!empty($courseCheckStatus)) {
                if ($courseCheckStatus == 'courseCheckStatus.finish') {
                    $status_sql = " and course_status ='" . trim($courseCheckStatus) . "'";
                } elseif ($courseCheckStatus == 'courseCheckStatus.all') {
                    $status_sql = " and course_status in ('courseCheckStatus.checked','courseCheckStatus.default')";
                }
            }
            
            $sql = "select distinct info.id,info.name,info.course_type,info.course_status,info.image_url,info.image,info.major_id,info.major_name,info.create_time,info.create_by from b_course_info info where info.del_flag=0 $status_sql $and";
            $sql .= " order by info.create_time desc ";
            $info = Yii::$app->db->createCommand($sql)->queryAll();
            if($info){
                foreach ($info as $key => $value) {
                    $u_sql = "SELECT pet_name FROM t_base_user_profile WHERE user_id=:userId AND del_flag=0";
                    $name = Yii::$app->db->createCommand($u_sql)->bindValue(':userId',$value['create_by'])->queryOne();
                    $info[$key]['user_name'] = $name['pet_name'];
                }
                $result = array(
                    "msg" => "查找成功",
                    "ver" => "1.5.0",
                    'data' => ['list' => $info],
                    'code' => '200'
                );
            }else{
                $result = array(
                    "msg" => "查找失敗",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(urldecode(json_encode($result)));
        }
    }
    //上面的方法适用于管理中心的所有用到的地方
    //本防晒适用于组课方面的所有用到的地方
    public function actionGetManageCenterCourseQuestion() {
        $error = array();
        $user_id = empty($_REQUEST['userId']) ?$error = array('用户id不能为空'): $_REQUEST['userId'] ;
        $roleType = empty($_REQUEST['roleType']) ?'': $_REQUEST['roleType'] ;
        $courseCheckStatus = isset($_REQUEST['courseCheckStatus']) ? $_REQUEST['courseCheckStatus'] : '';
        $projectId = empty($_REQUEST['projectId']) ?$error = array('联盟id不能为空'): $_REQUEST['projectId'] ;
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
//            $and = ' and 1=2';
            $and = " and info.project_id = '".$projectId."'";
//            if($roleType=='projectAdmin'){
////                if(!empty($projectId)){
//                    $and = " and info.project_id = '".$projectId."'";
////                }
//            }
//            if($roleType=='schoolAdmin'){
////                if(!empty($projectId)){
//                    $s_sql = "SELECT school_id,major_id FROM t_base_user_profile WHERE user_id='".$user_id."' AND del_flag=0";
//                    $school = Yii::$app->db->createCommand($s_sql)->queryOne();
//                    $and = " and info.school = '".$school['school_id']."' and info.project_id = '".$projectId."'";
////                }
//            }
//            if($roleType=='systemAdmin'){
//                $and = "";
//            }
            $status_sql = '';
//            if (!empty($courseCheckStatus)) {
//                if ($courseCheckStatus == 'courseCheckStatus.finish') {
//                    $status_sql = " and course_status ='" . trim($courseCheckStatus) . "'";
//                } elseif ($courseCheckStatus == 'courseCheckStatus.all') {
//                    $status_sql = " and course_status in ('courseCheckStatus.checked','courseCheckStatus.default')";
//                }
//            }
            
            $sql = "select distinct info.id,info.name,info.course_type,info.course_status,info.image_url,info.image,info.major_id,info.major_name,info.create_time,info.create_by from b_course_info info where 1=1 $status_sql $and";
            $sql .= " order by info.create_time desc ";
            $info = Yii::$app->db->createCommand($sql)->queryAll();
            if($info){
                foreach ($info as $key => $value) {
                    $u_sql = "SELECT pet_name FROM t_base_user_profile WHERE user_id=:userId AND del_flag=0";
                    $name = Yii::$app->db->createCommand($u_sql)->bindValue(':userId',$value['create_by'])->queryOne();
                    $info[$key]['user_name'] = $name['pet_name'];
                }
                $result = array(
                    "msg" => "查找成功",
                    "ver" => "1.5.0",
                    'data' => ['list' => $info],
                    'code' => '200'
                );
            }else{
                $result = array(
                    "msg" => "查找失敗",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(urldecode(json_encode($result)));
        }
    }
    //开课新建课表
    public function actionAddCourseSchedule(){
        $error = array();
        $t_course_id = empty($_REQUEST['t_course_id']) ?$error = array('开课课程id不能为空'): $_REQUEST['t_course_id'] ;
        $teacher_id = empty($_REQUEST['teacher_id']) ?$error = array('教师id不能为空'): $_REQUEST['teacher_id'] ;
        $class_id = empty($_REQUEST['class_id']) ?$error = array('班级id不能为空'): $_REQUEST['class_id'] ;
        $classIds=json_decode($class_id,true);
        $zhang_id = empty($_REQUEST['zhang_id']) ?$error = array('章id不能为空'): $_REQUEST['zhang_id'] ;
        $schedule_name = !isset($_REQUEST['schedule_name'])&&empty($_REQUEST['schedule_name']) ?$error = array('课表名称不能为空'): $_REQUEST['schedule_name'] ;
        $schedule_datetime = empty($_REQUEST['schedule_datetime']) ?$error = array('课表时间不能为空'): $_REQUEST['schedule_datetime'] ;
        $jie_id = empty($_REQUEST['jie_id']) ?'': $_REQUEST['jie_id'] ;
        if(empty($jie_id)){
           //如果章下没有小节
            $jie_id=$zhang_id;
            $zhang_id=0;
        }
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $create_time=date('Y-m-d H:i:s',time());
            $week=date('N', strtotime($schedule_datetime));
            $flag=0;
            $transaction = \Yii::$app->db->beginTransaction();
            try{
                //创建课表
                $t_course_schedule_id=Uuid::uuid();
                $sql="insert into t_course_schedule (id,schedule_name,t_course_id,teacher_id,date,week,begin_time,create_by,create_time,update_time,del_flag) "
                        . "values('".$t_course_schedule_id."','".addslashes($schedule_name)."','".$t_course_id."','".$teacher_id."','".$create_time."','".$week."','".$schedule_datetime."','".$teacher_id."','".$create_time."','".$create_time."',0)";
                $res=\yii::$app->db->createCommand($sql)->execute();
                if(!$res){
                    $flag=1;
                }
//                $classIds = array_unique($classIds);
                //关联课表与班级
                foreach ($classIds as $k=>$v){
                    $sql="insert into t_course_schedule_class (id,t_course_id,t_course_schedule_id,class_id,create_by,create_time,update_time,del_flag) values('".Uuid::uuid()."','".$t_course_id."','".$t_course_schedule_id."','".$v."','".$teacher_id."','".$create_time."','".$create_time."',0)";
                    $res=\yii::$app->db->createCommand($sql)->execute();
                    if(!$res){
                        $flag=1;
                    }
                }
                //关联课表与章节
                $sql="insert into t_course_schedule_chapter (id,t_course_item_id,t_course_item_pid,t_course_id,t_course_schedule_id,create_by,create_time,update_time,del_flag) values('".Uuid::uuid()."','".$jie_id."','".$zhang_id."','".$t_course_id."','".$t_course_schedule_id."','".$teacher_id."','".$create_time."','".$create_time."',0)";
                $res=\yii::$app->db->createCommand($sql)->execute();
                if(!$res){
                    $flag=1;
                }
            }catch (Exception $e){
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result, JSON_UNESCAPED_UNICODE));
            }
            if($flag==0){
                $transaction->commit();
                $result = array(
                    "msg" => "保存成功",
                    "ver" => "1.5.0",
                    'data' => ['create_time'=>$create_time,'t_course_schedule_id'=>$t_course_schedule_id],
                    'code' => '200'
                );
            }else{
                $transaction->rollBack();
                $result = array(
                    "msg" => "保存失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    //课表列表
    public function  actionGetCourseSchedule(){
        $error = array();
        $t_course_id = empty($_REQUEST['t_course_id']) ?$error = array('开课课程id不能为空'): $_REQUEST['t_course_id'] ;
        $type = empty($_REQUEST['type']) ?'teacher': $_REQUEST['type'] ;
        $me = empty($_REQUEST['me'])?'all':$_REQUEST['me'];
        $userid = empty($_REQUEST['userid'])?'':$_REQUEST['userid'];
        $allToday = empty($_REQUEST['all_day'])?'all':$_REQUEST['all_day'];
        if($type=='student'){
            $uid = empty($_REQUEST['student_id']) ?$error = array('学生id不能为空'): $_REQUEST['student_id'] ;
        }
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $where =' and 1=1 ';
            if($allToday == 'all'){
                $where =' and 1=1 ';
            }else{
                $startTime = date('Y-m-d', time())." 00:00:00";
                $endTime =   date('Y-m-d', time())." 23:59:59";
                $where =" and 1=1 and tcs.begin_time >'".$startTime."' and tcs.begin_time < '".$endTime."'";
            }
            if($me == 'all'){
                $sql="select tcs.id,tcs.schedule_name,tcs.date,tcs.week,p.pet_name,t_course_item_id,t_course_item_pid,tcs.begin_time from t_course_schedule tcs "
                    . "left join t_base_user_profile p on p.user_id=tcs.teacher_id "
                    . "left join t_course_schedule_chapter chapter on chapter.t_course_schedule_id=tcs.id "
                    . "where tcs.del_flag=0 and tcs.t_course_id='".$t_course_id."' $where order by tcs.create_time desc";
                $res=\yii::$app->db->createCommand($sql)->queryAll();
            }else{
                if(empty($userid) || empty($me)){
                    $result = array(
                        "msg" => "缺少请求参数",
                        "ver" => "1.5.0",
                        'data' => $error,
                        'code' => '601'
                    );
                    Yii::$app->end(json_encode($result));
                }
                $sql="select tcs.id,tcs.schedule_name,tcs.date,tcs.week,p.pet_name,t_course_item_id,t_course_item_pid,tcs.begin_time from t_course_schedule tcs "
                    . "left join t_base_user_profile p on p.user_id=tcs.teacher_id "
                    . "left join t_course_schedule_chapter chapter on chapter.t_course_schedule_id=tcs.id "
                    . "where tcs.del_flag=0 and tcs.t_course_id='".$t_course_id."' and tcs.create_by=:uid $where order by tcs.create_time desc";
                $res=\yii::$app->db->createCommand($sql)->bindValue(':uid', $userid)->queryAll();
            }
            $data=array();
            foreach ($res as $r){
                $sql="select class_id from t_course_schedule_class where t_course_schedule_id='".$r['id']."' and del_flag=0";
                $class_ids = \Yii::$app->db->createCommand($sql)->queryColumn();
                if($type=='student'){
                    //仅该班级下学员显示
                    $sql="select * from t_course_member where class_id in ('".implode("','", $class_ids)."') and del_flag=0 and course_id=:course_id and user_id=:uid";
                    $member=\yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$t_course_id,':uid'=>$uid])->queryAll();
                    if(empty($member)){
                        continue;
                    }
                }
                $sql="select class_name from t_base_class where id in ('". implode("','", $class_ids)."')";
                $classNames = \Yii::$app->db->createCommand($sql)->queryColumn();
                if($r['t_course_item_pid'] != '0'){
                    $sql="select title from t_course_item where id='".$r['t_course_item_pid']."'";
                    $chapter = \Yii::$app->db->createCommand($sql)->queryScalar();
                    $sql="select title from t_course_item where id='".$r['t_course_item_id']."'";
                    $jie = \Yii::$app->db->createCommand($sql)->queryScalar();
                    $chapter_str = $chapter.'>>'.$jie;
                }else{
                    $sql="select title from t_course_item where id='".$r['t_course_item_id']."'";
                    $chapter = \Yii::$app->db->createCommand($sql)->queryScalar();
                    $chapter_str = $chapter;
                }
                $data[]= array_merge($r,array('chapter'=>$chapter_str),array('class_name'=> implode(',', $classNames)),array('class_id'=> implode('|', $class_ids)));
            }
            if($res){
                $result = array(
                    "msg" => "查找成功",
                    "ver" => "1.5.0",
                    'data' => [$data],
                    'code' => '200'
                );
            }else{
                $result = array(
                    "msg" => "查找失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    //删除课表
    public function actionDeleteCourseSchedule(){
        $error = array();
        $t_course_id = empty($_REQUEST['tcourseId']) ?$error = array('开课课程id不能为空'): $_REQUEST['tcourseId'] ;
        $schedule_id = empty($_REQUEST['schedule_id']) ?$error = array('课表id不能为空'): $_REQUEST['schedule_id'] ;
        $teacher_id = empty($_REQUEST['teacher_id']) ?$error = array('教师id不能为空'): $_REQUEST['teacher_id'] ;
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $transaction=\yii::$app->db->beginTransaction();
            $flag=0;
            $update_time=date('Y-m-d H:i:s',time());
            try{
                //删除课表
                $sql="update t_course_schedule set del_flag=1,update_by='".$teacher_id."',update_time='".$update_time."' where id='".$schedule_id."' and teacher_id='".$teacher_id."' and t_course_id='".$t_course_id."'";
                $res=\yii::$app->db->createCommand($sql)->execute();
                if(!$res){
                    $flag=1;
                }
                //删除课表班级关联关系
                $sql="update t_course_schedule_class set del_flag=1,update_by='".$teacher_id."',update_time='".$update_time."' where t_course_schedule_id='".$schedule_id."' and t_course_id='".$t_course_id."'";
                $res=\yii::$app->db->createCommand($sql)->execute();
                if(!$res){
                    $flag=1;
                }
                //删除课表章节关联关系
                $sql="update t_course_schedule_chapter set del_flag=1,update_by='".$teacher_id."',update_time='".$update_time."' where t_course_schedule_id='".$schedule_id."' and t_course_id='".$t_course_id."'";
                $res=\yii::$app->db->createCommand($sql)->execute();
                if(!$res){
                    $flag=1;
                }
            }catch (Exception $e){
                $result = array(
                    "msg" => "更新失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '500'
                );
                Yii::$app->end(json_encode($result));
            }
            if($flag==0){
                $transaction->commit();
                $result = array(
                    "msg" => "更新成功",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '200'
                );
            }else{
                $transaction->rollBack();
                $result = array(
                    "msg" => "更新失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    
    public function actionScheduleInfo(){
        $scheduleId = empty($_REQUEST['id'])?$error=['上课ID不能为空']:$_REQUEST['id'];
        $sql="select t_course_item_id,t_course_item_pid from t_course_schedule_chapter where t_course_schedule_id='".$scheduleId."' and del_flag=0";        
        $chapters = \Yii::$app->db->createCommand($sql)->queryOne();
        $sql="select * from t_course_schedule where id='".$scheduleId."'";
        $scheduleInfo = \Yii::$app->db->createCommand($sql)->queryOne();
        $sql="select * from t_course_schedule_task where t_course_schedule_id='".$scheduleId."' and del_flag=0";
        $task = \Yii::$app->db->createCommand($sql)->queryAll();
        $sql="select * from t_course_schedule_sign where t_course_schedule_id='".$scheduleId."' and del_flag=0";
        $sign = \Yii::$app->db->createCommand($sql)->queryAll();
        $quiz_sql="select * from t_course_schedule_quiz where t_course_schedule_id='".$scheduleId."' and del_flag=0";
        $quiz = \Yii::$app->db->createCommand($quiz_sql)->queryAll();
        //课程教学--随堂考  已发布的所有考试测验里面属于随堂考的卷子，然后再查测验
        $paperIds=array();
        foreach($quiz as $val){
            $paper_id = TQuizPaperRelation::find()->where(['quiz_id'=>$val['quiz_id'],'del_flag'=>0])->one()->paper_id;
            $paperIds[] = $paper_id;
        }
        $paperId = implode("','", $paperIds);
        $paper_sql = "select sq.* from t_quiz_paper p "
                . "left join t_quiz_paper_relation r on r.paper_id=p.id "
                . "left join t_course_schedule_quiz sq on sq.quiz_id=r.quiz_id "
                . " where p.id in('".$paperId."') and p.type='quizType.quiz.class' and sq.t_course_schedule_id='".$scheduleId."' and sq.del_flag=0 and p.del_flag=0";
        $quizClass = Yii::$app->db->createCommand($paper_sql)->queryAll();
 
        $result = array(
                "msg" => "更新成功",
                "ver" => "1.5.0",
                'data' => ['chapter'=>$chapters,'scheduleInfo'=>$scheduleInfo,'task'=>$task,'sign'=>$sign,'quiz'=>$quiz,'quizClass'=>$quizClass],
                'code' => '200'
            );
        Yii::$app->end(json_encode($result));
    }

    //课堂教学查看分组详情
    public function actionGetTaskDetails(){
        $t_course_id = empty($_REQUEST['tcourseId']) ?$error = array('开课课程id不能为空'): $_REQUEST['tcourseId'] ;
        $schedule_id = empty($_REQUEST['schedule_id']) ?$error = array('课表id不能为空'): $_REQUEST['schedule_id'] ;
        $class_id = empty($_REQUEST['class_id']) ?$error = array('班级id不能为空'): $_REQUEST['class_id'] ;
        $study_type = empty($_REQUEST['study_type']) ? 'studyType.preview': $_REQUEST['study_type'] ;
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            //主任务
            $cids=explode('|',$class_id);
            $str="";
            foreach($cids as $k=>$v){
                $str.="'".$v."',";
            }
            $classIds=rtrim($str,",");
            //为该班级下学生创建报告记录
            $sql="select user_id from t_course_member where course_id=:t_course_id and del_flag=0 and class_id in ($classIds)";
            $uidList=Yii::$app->db->createCommand($sql)->bindValues([':t_course_id'=>$t_course_id])->queryColumn();
            $str="";
            foreach($uidList as $k=>$v){
                $str.="'".$v."',";
            }
            $uids=rtrim($str,",");
            $sql="SELECT
	*
FROM
	t_course_task t
LEFT JOIN t_course_schedule_task st ON t.id = st.task_id
WHERE
	st.del_flag = 0
AND t.del_flag=0
AND st.t_course_id =:t_course_id
AND st.t_course_schedule_id =:t_course_schedule_id and study_type=:study_type ORDER BY t.create_time desc,t.task_title";
            $taksList=\yii::$app->db->createCommand($sql)->bindValues([':t_course_id'=>$t_course_id,':t_course_schedule_id'=>$schedule_id,':study_type'=>$study_type])->queryAll();
            if(!empty($taksList)){
                foreach($taksList as $k=>$v){
                    $sql="select d.name,tr.*,p.user_id,p.pet_name,p.student_no from t_course_task_report tr left join t_sys_dictionary d on d.value=tr.report_status left join t_base_user_profile p on tr.create_by=p.user_id  where p.del_flag=0 and tr.create_by in (".$uids.") and tr.del_flag=0 and tr.task_id=:task_id";
                    $info=\yii::$app->db->createCommand($sql)->bindValues([':task_id'=>$v['task_id']])->queryAll();
                    $data[$v['task_id']]=$info;
                }
                if($data){
                    $result = array(
                        "msg" => "查找成功",
                        "ver" => "1.5.0",
                        'data' => ['taskList'=>$taksList,'finishedInfo'=>$data],
                        'code' => '200'
                    );
                }else{
                    $result = array(
                        "msg" => "查找失败",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '400'
                    );
                }
            }else{
                $result = array(
                    "msg" => "查找成功",
                    "ver" => "1.5.0",
                    'data' => ['taskList'=>[],'finishedInfo'=>[]],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    //课堂学习（学生）
    public function actionGetTaskDetailsForStudent(){
        $tcourseId = empty($_REQUEST['tcourseId']) ?$error = array('开课课程id不能为空'): $_REQUEST['tcourseId'] ;
        $schedule_id = empty($_REQUEST['schedule_id']) ?$error = array('课表id不能为空'): $_REQUEST['schedule_id'] ;
        $student_id = empty($_REQUEST['student_id']) ?$error = array('学生id不能为空'): $_REQUEST['student_id'] ;
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $sql="SELECT tr.*, t.task_title FROM
	      t_course_task_report tr
LEFT JOIN t_course_task t ON t.id = tr.task_id
LEFT JOIN t_course_schedule_task st ON t.id = st.task_id
WHERE
	tr.create_by =:student_id
AND st.t_course_id =:tcourseId
AND st.t_course_schedule_id = :schedule_id
AND t.del_flag = 0
AND tr.del_flag = 0
AND st.del_flag = 0
";
            $res=\yii::$app->db->createCommand($sql)->bindValues([':student_id'=>$student_id,':tcourseId'=>$tcourseId,':schedule_id'=>$schedule_id])->queryAll();
            $info[]=$res;
                if($info){
                    $result = array(
                        "msg" => "查找成功",
                        "ver" => "1.5.0",
                        'data' => $info,
                        'code' => '200'
                    );
                }else{
                    $result = array(
                        "msg" => "查找失败",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '400'
                    );
                }
            Yii::$app->end(json_encode($result));
        }
    }
    //课堂教学  作业  查看详情
    public function actionGetQuizInfo(){
        $error = array();
        $t_course_id = empty($_REQUEST['tcourseId']) ?$error = array('开课课程id不能为空'): $_REQUEST['tcourseId'] ;
        $schedule_id = empty($_REQUEST['schedule_id']) ?$error = array('课表id不能为空'): $_REQUEST['schedule_id'] ;
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $sql="select * from t_quiz_info t left join t_course_schedule_quiz st on t.id=st.quiz_id where st.del_flag=0 and st.t_course_id='".$t_course_id."' and st.t_course_schedule_id='".$schedule_id."'";
            $quizInfoList=\yii::$app->db->createCommand($sql)->queryAll();

            foreach($quizInfoList as $k=>$v){
//                $result_sql = "select d.name,r.*,p.user_id,p.pet_name,p.student_no from t_quiz_result r left join t_sys_dictionary d on d.value=r.status left join t_base_user_profile p on r.create_by=p.user_id  where  r.quiz_id='".$v['quiz_id']."' and r.del_flag=0";
                $result_sql = "select r.*,p.user_id,p.pet_name,p.student_no from t_quiz_result r "
                        . "left join t_base_user_profile p on r.create_by=p.user_id "
                        . " where  r.quiz_id='".$v['quiz_id']."' and r.del_flag=0";
                $info=\yii::$app->db->createCommand($result_sql)->queryAll();
                $data[$v['quiz_id']]=$info;
            }
            if($data){
                $result = array(
                    "msg" => "查找成功",
                    "ver" => "1.5.0",
                    'data' => ['quizInfoList'=>$quizInfoList,'finishedInfo'=>$data],
                    'code' => '200'
                );
            }else{
                $result = array(
                    "msg" => "查找失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    
    
    /**
     * 获取课程
     */
    public function actionTestQuizList() {
        $error = array();
        $course_id = empty($_REQUEST['tcourseId'])?$error[]=array('开课ID不能为空'):$_REQUEST['tcourseId'];
        $Bcourse_id = empty($_REQUEST['bcourseId'])?$error[]=array('课程模板ID不能为空'):$_REQUEST['bcourseId'];
//        $projectId = empty($_REQUEST['projectId'])?$error[]=array('联盟ID不能为空'):$_REQUEST['projectId'];
        $scheduleId = empty($_REQUEST['scheduleId'])?$error[]=array('课表ID不能为空'):$_REQUEST['scheduleId'];
        $keywords=isset($_REQUEST['keywords'])?$_REQUEST['keywords']:'';
        $publishStatus=isset($_REQUEST['publishStatus'])?$_REQUEST['publishStatus']:'';
        $page = isset($_REQUEST['page'])?$_REQUEST['page']:1;
        $pageSize = isset($_REQUEST['pageSize'])?$_REQUEST['pageSize']:5;
        if(!isset($page)||$page==1) {
            $page = 1;
            $limit=$pageSize*($page-1);
        }else{
            $limit=$pageSize*($page-1);
        }
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
    	}else{
            $transaction = \Yii::$app->db->beginTransaction();
            try {
//                $sql = "select qf.*,r.paper_id from t_quiz_info qf "
//                        . "left join t_quiz_paper_relation r on r.quiz_id=qf.id "
//                        . " where qf.b_course_id='".$Bcourse_id."' and qf.t_course_id='".$course_id."' and qf.del_flag=0 and r.del_flag=0";
                $sql = "select qf.*,r.paper_id,p.type as paper_type from t_quiz_info qf "
                        . "left join t_quiz_paper_relation r on r.quiz_id=qf.id "
                        ." left join t_quiz_paper p on p.id=r.paper_id "
                        . " where qf.b_course_id='".$Bcourse_id."' and qf.t_course_id='".$course_id."' and qf.quiz_status in ('activityStatus.checked','activityStatus.ongoing') and qf.del_flag=0 and r.del_flag=0";
                $where="";
                if(!empty($keywords)){
                    $where.=" AND qf.quiz_name like '%".$keywords."%' ";
                }
                if(!empty($publishStatus)){
                    $where.=" AND qf.quiz_status='".$publishStatus."' ";
                }
                $where.=" order by create_time desc";
                $sql=$sql.$where;
                $count = \Yii::$app->db->createCommand($sql)->queryAll();
//                $sql.=" limit ".$limit.",".$pageSize;
                $info= \Yii::$app->db->createCommand($sql)->queryAll();
                foreach($info as $key=>$val){
                    $paper = TQuizPaperRelation::find()->where(['quiz_id'=>$val['id']])->one();
                    //查询本卷是否有试题
                    $paperQues = TQuizPaperQuesRelation::find()->where(['paper_id'=>$paper->paper_id,'del_flag'=>0])->all();
                    if(empty($paperQues)){
                        $isQues = 0;
                    }else{
                        $isQues = 1;
                    }
                    //查询课堂教学是否已发布
                    $scheduel = TCourseScheduleQuiz::find()->where(['t_course_id'=>$course_id,'t_course_schedule_id'=>$scheduleId,'quiz_id'=>$val['id'],'del_flag'=>0])->all();
                    if(empty($scheduel)){
                        $isSchedule = 0;
                    }else{
                        $isSchedule = 1;
                    }
                    $info[$key] = array_merge($val,array('isQues'=>$isQues,'isSchedule'=>$isSchedule));
                }
                $transaction->commit();
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => array_merge(array('sum'=> count($count),'info'=>$info)),
                    'code' => '200',
                ];
            } catch (Exception $e) {
                $transaction->rollBack();
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'code' => '500'
                ];
            }
        }
        Yii::$app->end(json_encode($result));
    }
    
    //更改作业测验状态
    public function actionQuizStatusChange(){
        $error = array();
        $mongoDate = array();
        $loginData = array();
        $quiz_id = empty($_REQUEST['id'])?$error[]=array('测验ID不能为空'):$_REQUEST['id'];
        $quiz_status = empty($_REQUEST['quiz_status'])?$error[]=array('测验状态不能为空'):$_REQUEST['quiz_status'];
        $userId = empty($_REQUEST['userId'])?$error[]=array('用户id不能为空'):$_REQUEST['userId'];
//        $back = empty($_REQUEST['back'])?$error[]=array('回退标识不能为空'):$_REQUEST['back'];
        $tcourseId = empty($_REQUEST['tcourseId'])?$error[]=array('开课ID不能为空'):$_REQUEST['tcourseId'];
        $bcourseId = empty($_REQUEST['bcourseId'])?$error[]=array('课程模板ID不能为空'):$_REQUEST['bcourseId'];
//        $quizId = empty($_REQUEST['quizId'])?$error[]=array('作业测验ID不能为空'):$_REQUEST['quizId'];
        $classIds = empty($_REQUEST['classIds'])?$error[]=array('班级ID不能为空'):$_REQUEST['classIds'];
        $time = empty($_REQUEST['time'])?$error[]=array('时间不能为空'):$_REQUEST['time'];
        
        $tcourseScheduleId= isset($_REQUEST['tcourseScheduleId']) && !empty($_REQUEST['tcourseScheduleId']) ? $_REQUEST['tcourseScheduleId']:$error[]='教学ID不能为空';
        $fabu = isset($_REQUEST['fabu']) && !empty($_REQUEST['fabu']) ?$_REQUEST['fabu']:'';
        
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                $quizIds = explode('","', trim($quiz_id,'"'));
            //更改考试测验状态
            $sql = "update t_quiz_info set quiz_status='".$quiz_status."',update_by='".$userId."' , update_time='".date('Y-m-d H:i:s')."' where id in (".$quiz_id.")";
            $res = Yii::$app->db->createCommand($sql)->execute();
            if($res !=false){
                $quizFlag = true;
                //查询学员是否已发放
                //查询已发人员
                $result_sql = "select create_by from t_quiz_result  where quiz_id='".$quiz_id."' and del_flag=0";
                $result_user_id = \Yii::$app->db->createCommand($result_sql)->queryColumn();
                //查询本班级下的所有学员
//                $member_sql = "select user_id from t_course_member where class_id='".$classId."' and course_id='".$tcourseId."' and del_flag=0";
                $member_sql = "select user_id from t_course_member where class_id in (".$classIds.") and course_id='".$tcourseId."' and del_flag=0";
                $member_user_id = \Yii::$app->db->createCommand($member_sql)->queryColumn();
                //需要补发的学员id
                $reissue_user_id = array_diff($member_user_id, $result_user_id);
                foreach ($quizIds as $k=>$id){
                    foreach($reissue_user_id as $val){
                        $result = new TQuizResult();
                        $result->id = Uuid::uuid();
                        $result->quiz_id = $id;
                        $result->create_by = $val;
                        $result->create_time = date('Y-m-d H:i:s');
                        $result->del_flag = 0;
                        $result->status = "";
                        $result->is_invalid = "";
                        $result->is_evaluated = "";
                        $resultRes = $result->save();
                        if($resultRes !=false){
                            $resultFlag = true;
                            $info = TCourseScheduleQuiz::find()->where(['t_course_id'=>$tcourseId,'t_course_schedule_id'=>$tcourseScheduleId,'quiz_id'=>$id,'del_flag'=>0])->all();
                            if(empty($info)){
                                $model = new TCourseScheduleQuiz();
                                $model->id = Uuid::uuid();
                                $model->t_course_id = $tcourseId;
                                $model->t_course_schedule_id = $tcourseScheduleId;
                                $model->quiz_id = $id;
                                $model->create_by = $userId;
                                $model->create_time = date('Y-m-d H:i:s');
                                $model->del_flag = 0;
                                $scheduleRes = $model->save();
                                if($scheduleRes !=false){
                                    $scheduleFlag = true;
                                }else{
                                    $scheduleFlag = false;
                                }
                            }else{
                                $scheduleFlag = true;
                            }
                        }else{
                            $resultFlag = false;
                        }
                        
                    }
                
                if($result->status==''){
                        $status = '未做';
                    }elseif($result->status=='quizResultStatus.answerIn'){
                        $status = '答题中';
                    }elseif($result->status=='quizResultStatus.submitted'){
                        $status = '已提交';
                    }elseif($result->status=='quizResultStatus.marked'){
                        $status = '已批阅';
                    }
                    $mongoDate[$k]['tasksEvaluationid'] = $result->id;
                    $mongoDate[$k]['userid'] = $val;
                    $mongoDate[$k]['status'] = $status;
                    $mongoDate[$k]['learningTasksid'] = $id;
                    $mongoDate[$k]['launchCourseid'] = $tcourseId;
                    $mongoDate[$k]['startdotime'] = $time;
                    $mongoDate[$k]['submittime'] = $time;
                    $mongoDate[$k]['grater'] = $result->update_by==''?$result->create_by:$result->update_by;
                    $mongoDate[$k]['gradetime'] = $$time;
                                        
//                    $loginData[] = $result->id;
            }
            }else{
                $quizFlag = false;
            }
            if($quizFlag && $resultFlag && $scheduleFlag){
                $transaction->commit();
                $result = [
                    'msg' => '学员答题卡插入成功',
                    'ver' => '1.5.0',
                    'data' => array_merge(array('mongoDate'=>$mongoDate),array('loginData'=>$loginData)),
                    'code' => '200',
                ];
            }else{
                $transaction->rollBack();
                $result = [
                    'msg' => '学员答题卡插入失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '500'
                ];
            }
            Yii::$app->end(json_encode($result));
            } catch (Exception $e) {
                $transaction->rollBack();
                $result = [
                    'msg' => '学员答题卡插入失败',
                    'ver' => '1.5.0',
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }
    
//    public function actionPublishStudentResultAll(){
//        $error = array();
//        $mongoDate = array();
//        $loginData = array();
//        $tcourseId = empty($_REQUEST['tcourseId'])?$error[]=array('开课ID不能为空'):$_REQUEST['tcourseId'];
//        $bcourseId = empty($_REQUEST['bcourseId'])?$error[]=array('课程模板ID不能为空'):$_REQUEST['bcourseId'];
//        $quizId = empty($_REQUEST['quizId'])?$error[]=array('作业测验ID不能为空'):$_REQUEST['quizId'];
//        $classIds = empty($_REQUEST['classIds'])?$error[]=array('班级ID不能为空'):$_REQUEST['classIds'];
//        if(!empty($error)){
//            $result = [
//                'msg' => '缺少请求参数',
//                'ver' => '1.5.0',
//                'data' => $error,
//                'code' => '601',
//            ];
//        }else{
//            $transaction = \Yii::$app->db->beginTransaction();
//            try {
//                $quizIds = explode('","', trim($quizId,'"'));
//            $users_sql = "select user_id from t_course_member m where class_id in (".$classIds.") and course_id='".$tcourseId."' and del_flag=0";
//            $users = Yii::$app->db->createCommand($users_sql)->queryColumn();
//            foreach ($users as $val){
//                foreach($quizIds as $k=>$id){
//                    $userResult = TQuizResult::find()->where(['create_by'=>$val,'quiz_id'=>$id,'del_flag'=>0])->one();
//                    if(empty($userResult)){
//                        $result = new TQuizResult();
//                        $result->id = Uuid::uuid();
//                        $result->quiz_id = $id;
//                        $result->create_by = $val;
//                        $result->create_time = date('Y-m-d H:i:s');
//                        $result->del_flag = 0;
//                        $result->status = "";
//                        $result->is_invalid = "";
//                        $result->is_evaluated = "";
//                        $resultRes = $result->save();
//                        if($resultRes !=false){
//                            $resultFlag = true;
//                        }else{
//                            $resultFlag = false;
//                        }
//                    }else{
//                        continue;
//                    }
//                    if($result->status==''){
//                        $status = '未做';
//                    }elseif($result->status=='quizResultStatus.answerIn'){
//                        $status = '答题中';
//                    }elseif($result->status=='quizResultStatus.submitted'){
//                        $status = '已提交';
//                    }elseif($result->status=='quizResultStatus.marked'){
//                        $status = '已批阅';
//                    }
//                    $mongoDate[$k]['tasksEvaluationid'] = $result->id;
//                    $mongoDate[$k]['userid'] = $val;
//                    $mongoDate[$k]['status'] = $status;
//                    $mongoDate[$k]['learningTasksid'] = $id;
//                    $mongoDate[$k]['launchCourseid'] = $tcourseId;
//                    $mongoDate[$k]['startdotime'] = $result->update_time==''?$result->create_time:$result->update_time;
//                    $mongoDate[$k]['submittime'] = $result->update_time==''?$result->create_time:$result->update_time;
//                    $mongoDate[$k]['grater'] = $result->update_by==''?$result->create_by:$result->update_by;
//                    $mongoDate[$k]['gradetime'] = $result->create_time;
//                                        
////                    $loginData[$k]['userid'] = \Yii::$app->user->identity->id;
////                    $loginData[$k]['time'] = $result->update_time==''?$result->create_time:$result->update_time;
////                    $loginData[$k]['ip'] = \Yii::$app->request->userIP;
////                    $loginData[$k]['equipment'] = PdUtils::EQUIPMENT_PC;
////                    $loginData[$k]['operation_code'] = '10060052';
////                    $loginData[$k]['operation_name'] = '导入考试测验';
////                    $loginData[$k]['courseid'] = $bcourseId;
////                    $loginData[$k]['objectid'] = $result->id;
//                    $loginData[] = $result->id;
//                }
//            }
//           
//            if($resultFlag){
//                $transaction->commit();
//                $result = [
//                    'msg' => '学员答题卡插入成功',
//                    'ver' => '1.5.0',
//                    'data' => array_merge(array('mongoDate'=>$mongoDate),array('loginData'=>$loginData)),
//                    'code' => '200',
//                ];
//            }else{
//                $transaction->rollBack();
//                $result = [
//                    'msg' => '学员答题卡插入失败',
//                    'ver' => '1.5.0',
//                    'data' => [],
//                    'code' => '500'
//                ];
//            }
//            Yii::$app->end(json_encode($result));
//            } catch (Exception $e) {
//                $transaction->rollBack();
//                $result = [
//                    'msg' => '学员答题卡插入失败',
//                    'ver' => '1.5.0',
//                    'code' => '500'
//                ];
//                Yii::$app->end(json_encode($result));
//            }
//        }
//    }
    
    //随堂考
    //课堂教学  作业  查看详情
    public function actionGetQuizClassInfo(){
        $error = array();
        $t_course_id = empty($_REQUEST['tcourseId']) ?$error = array('开课课程id不能为空'): $_REQUEST['tcourseId'] ;
        $schedule_id = empty($_REQUEST['schedule_id']) ?$error = array('课表id不能为空'): $_REQUEST['schedule_id'] ;
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少请求参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
//            $sql="select * from t_quiz_info t left join t_course_schedule_quiz st on t.id=st.quiz_id where st.del_flag=0 and st.t_course_id='".$t_course_id."' and st.t_course_schedule_id='".$schedule_id."'";
            $sql="select * from t_quiz_info t "
                    . "left join t_course_schedule_quiz st on t.id=st.quiz_id "
                    . "left join t_quiz_paper_relation r on r.quiz_id=t.id "
                    . "left join t_quiz_paper p on p.id=r.paper_id "
                    . "where st.del_flag=0 and p.type='quizType.quiz.class' and st.t_course_id='".$t_course_id."' and st.t_course_schedule_id='".$schedule_id."'";
            $quizInfoList=\yii::$app->db->createCommand($sql)->queryAll();
            foreach($quizInfoList as $k=>$v){
//                $result_sql = "select d.name,r.*,p.user_id,p.pet_name,p.student_no from t_quiz_result r left join t_sys_dictionary d on d.value=r.status left join t_base_user_profile p on r.create_by=p.user_id  where  r.quiz_id='".$v['quiz_id']."' and r.del_flag=0";
                $result_sql = "select r.*,p.user_id,p.pet_name,p.student_no from t_quiz_result r "
                        . "left join t_base_user_profile p on r.create_by=p.user_id "
                        . " where  r.quiz_id='".$v['quiz_id']."' and r.del_flag=0";
                $info=\yii::$app->db->createCommand($result_sql)->queryAll();
                $data[$v['quiz_id']]=$info;
            }
            if($data){
                $result = array(
                    "msg" => "查找成功",
                    "ver" => "1.5.0",
                    'data' => ['quizInfoList'=>$quizInfoList,'finishedInfo'=>$data],
                    'code' => '200'
                );
            }else{
                $result = array(
                    "msg" => "查找失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    
    /**
     * 获取课程
     */
    public function actionTestQuizClassList() {
        $error = array();
        $course_id = empty($_REQUEST['tcourseId'])?$error[]=array('开课ID不能为空'):$_REQUEST['tcourseId'];
        $Bcourse_id = empty($_REQUEST['bcourseId'])?$error[]=array('课程模板ID不能为空'):$_REQUEST['bcourseId'];
//        $projectId = empty($_REQUEST['projectId'])?$error[]=array('联盟ID不能为空'):$_REQUEST['projectId'];
        $scheduleId = empty($_REQUEST['scheduleId'])?$error[]=array('课表ID不能为空'):$_REQUEST['scheduleId'];
        $keywords=isset($_REQUEST['keywords'])?$_REQUEST['keywords']:'';
        $publishStatus=isset($_REQUEST['publishStatus'])?$_REQUEST['publishStatus']:'';
        $page = isset($_REQUEST['page'])?$_REQUEST['page']:1;
        $pageSize = isset($_REQUEST['pageSize'])?$_REQUEST['pageSize']:5;
        if(!isset($page)||$page==1) {
            $page = 1;
            $limit=$pageSize*($page-1);
        }else{
            $limit=$pageSize*($page-1);
        }
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
    	}else{
            $transaction = \Yii::$app->db->beginTransaction();
            try {
//                $sql = "select qf.*,r.paper_id from t_quiz_info qf "
//                        . "left join t_quiz_paper_relation r on r.quiz_id=qf.id "
//                        . " where qf.b_course_id='".$Bcourse_id."' and qf.t_course_id='".$course_id."' and qf.del_flag=0 and r.del_flag=0";
                $sql = "select qf.*,r.paper_id,p.type as paper_type from t_quiz_info qf "
                        . "left join t_quiz_paper_relation r on r.quiz_id=qf.id "
                        ." left join t_quiz_paper p on p.id=r.paper_id "
                        . " where qf.b_course_id='".$Bcourse_id."' and p.type='quizType.quiz.class' and qf.t_course_id='".$course_id."' and qf.del_flag=0 and r.del_flag=0";
                $where="";
                if(!empty($keywords)){
                    $where.=" AND qf.quiz_name like '%".$keywords."%' ";
                }
                if(!empty($publishStatus)){
                    $where.=" AND qf.quiz_status='".$publishStatus."' ";
                }
                $where.=" order by create_time desc";
                $sql=$sql.$where;
                $count = \Yii::$app->db->createCommand($sql)->queryAll();
//                $sql.=" limit ".$limit.",".$pageSize;
                $info= \Yii::$app->db->createCommand($sql)->queryAll();
                foreach($info as $key=>$val){
                    $paper = TQuizPaperRelation::find()->where(['quiz_id'=>$val['id']])->one();
                    //查询本卷是否有试题
                    $paperQues = TQuizPaperQuesRelation::find()->where(['paper_id'=>$paper->paper_id,'del_flag'=>0])->all();
                    if(empty($paperQues)){
                        $isQues = 0;
                    }else{
                        $isQues = 1;
                    }
                    //查询课堂教学是否已发布
                    $scheduel = TCourseScheduleQuiz::find()->where(['t_course_id'=>$course_id,'t_course_schedule_id'=>$scheduleId,'quiz_id'=>$val['id'],'del_flag'=>0])->all();
                    if(empty($scheduel)){
                        $isSchedule = 0;
                    }else{
                        $isSchedule = 1;
                    }
                    $info[$key] = array_merge($val,array('isQues'=>$isQues,'isSchedule'=>$isSchedule));
                }
                $transaction->commit();
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => array_merge(array('sum'=> count($count),'info'=>$info)),
                    'code' => '200',
                ];
            } catch (Exception $e) {
                $transaction->rollBack();
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'code' => '500'
                ];
            }
        }
        Yii::$app->end(json_encode($result));
    }
    
    //考试作业单个发布
    public function actionQuizPaperSingle(){
        $error = array();
        $mongoDate = array();
        $loginData = array();
        $quiz_id = empty($_REQUEST['id'])?$error[]='测验ID不能为空':$_REQUEST['id'];
        $quiz_status = empty($_REQUEST['quiz_status'])?$error[]='测验状态不能为空':$_REQUEST['quiz_status'];
        $userId = empty($_REQUEST['userId'])?$error[]='用户id不能为空':$_REQUEST['userId'];
//        $back = empty($_REQUEST['back'])?$error[]=array('回退标识不能为空'):$_REQUEST['back'];
        $tcourseId = empty($_REQUEST['tcourseId'])?$error[]='开课ID不能为空':$_REQUEST['tcourseId'];
        $bcourseId = empty($_REQUEST['bcourseId'])?$error[]='课程模板ID不能为空':$_REQUEST['bcourseId'];
//        $quizId = empty($_REQUEST['quizId'])?$error[]=array('作业测验ID不能为空'):$_REQUEST['quizId'];
        $classId = empty($_REQUEST['classIds'])?$error[]='班级ID不能为空':$_REQUEST['classIds'];
        $time = empty($_REQUEST['time'])?$error[]='时间不能为空':$_REQUEST['time'];
        
        $tcourseScheduleId= isset($_REQUEST['tcourseScheduleId']) && !empty($_REQUEST['tcourseScheduleId']) ? $_REQUEST['tcourseScheduleId']:$error[]='教学ID不能为空';
        $fabu = isset($_REQUEST['fabu']) && !empty($_REQUEST['fabu']) ?$_REQUEST['fabu']:'';
        
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $transaction = \Yii::$app->db->beginTransaction();
            try {
            //更改考试测验状态
//                $model = \app\models\TQuizInfo::findOne($quiz_id);
//                if($model->quiz_status=='activityStatus.checked'){
                    $sql = "update t_quiz_info set quiz_status='".$quiz_status."',update_by='".$userId."' , update_time='".date('Y-m-d H:i:s')."' where id in ('".$quiz_id."')";
                    $res = Yii::$app->db->createCommand($sql)->execute();
//                }else{
//                    $res = true;
//                }
            
            if($res !=false){
                $quizFlag = true;
                //查询学员是否已发放
                //查询已发人员
                $result_sql = "select create_by from t_quiz_result  where quiz_id='".$quiz_id."' and del_flag=0";
                $result_user_id = \Yii::$app->db->createCommand($result_sql)->queryColumn();
                //查询本班级下的所有学员
//                $member_sql = "select user_id from t_course_member where class_id='".$classId."' and course_id='".$tcourseId."' and del_flag=0";
                $member_sql = "select user_id from t_course_member where class_id in (".$classId.") and course_id='".$tcourseId."' and del_flag=0";
                $member_user_id = \Yii::$app->db->createCommand($member_sql)->queryColumn();
                //需要补发的学员id
                $reissue_user_id = array_diff($member_user_id, $result_user_id);
                if(!empty($reissue_user_id)){
                    foreach($reissue_user_id as $k=>$val){
                        $result = new TQuizResult();
                        $result->id = Uuid::uuid();
                        $result->quiz_id = $quiz_id;
                        $result->create_by = $val;
                        $result->create_time = date('Y-m-d H:i:s');
                        $result->del_flag = 0;
                        $result->status = "";
                        $result->is_invalid = "";
                        $result->is_evaluated = "";
                        $resultRes = $result->save();
                        if($resultRes !=false){
                            $resultFlag = true;
                            $info = TCourseScheduleQuiz::find()->where(['t_course_id'=>$tcourseId,'t_course_schedule_id'=>$tcourseScheduleId,'quiz_id'=>$quiz_id,'del_flag'=>0])->all();
                            if(empty($info)){
                                $model = new TCourseScheduleQuiz();
                                $model->id = Uuid::uuid();
                                $model->t_course_id = $tcourseId;
                                $model->t_course_schedule_id = $tcourseScheduleId;
                                $model->quiz_id = $quiz_id;
                                $model->create_by = $userId;
                                $model->create_time = date('Y-m-d H:i:s');
                                $model->del_flag = 0;
                                $scheduleRes = $model->save();
                                if($scheduleRes !=false){
                                    $scheduleFlag = true;
                                }else{
                                    $scheduleFlag = false;
                                }
                            }else{
                                $scheduleFlag = true;
                            }

                        }else{
                            $resultFlag = false;
                        }
                    if($result->status==''){
                            $status = '未做';
                        }elseif($result->status=='quizResultStatus.answerIn'){
                            $status = '答题中';
                        }elseif($result->status=='quizResultStatus.submitted'){
                            $status = '已提交';
                        }elseif($result->status=='quizResultStatus.marked'){
                            $status = '已批阅';
                        }
                        $mongoDate[$k]['tasksEvaluationid'] = $result->id;
                        $mongoDate[$k]['userid'] = $val;
                        $mongoDate[$k]['status'] = $status;
                        $mongoDate[$k]['learningTasksid'] = $quiz_id;
                        $mongoDate[$k]['launchCourseid'] = $tcourseId;
                        $mongoDate[$k]['startdotime'] = $time;
                        $mongoDate[$k]['submittime'] = $time;
                        $mongoDate[$k]['grater'] = $result->update_by==''?$result->create_by:$result->update_by;
                        $mongoDate[$k]['gradetime'] = $time;

    //                    $loginData[] = $result->id;
                }
                }else{
                    $resultFlag = true;
                    $info = TCourseScheduleQuiz::find()->where(['t_course_id'=>$tcourseId,'t_course_schedule_id'=>$tcourseScheduleId,'quiz_id'=>$quiz_id,'del_flag'=>0])->all();
                    if(empty($info)){
                        $model = new TCourseScheduleQuiz();
                        $model->id = Uuid::uuid();
                        $model->t_course_id = $tcourseId;
                        $model->t_course_schedule_id = $tcourseScheduleId;
                        $model->quiz_id = $quiz_id;
                        $model->create_by = $userId;
                        $model->create_time = date('Y-m-d H:i:s');
                        $model->del_flag = 0;
                        $scheduleRes = $model->save();
                        if($scheduleRes !=false){
                            $scheduleFlag = true;
                        }else{
                            $scheduleFlag = false;
                        }
                    }else{
                        $scheduleFlag = true;
                    }
                }
            }else{
                $quizFlag = false;
            }
            if($quizFlag && $resultFlag && $scheduleFlag){
                $transaction->commit();
                $result = [
                    'msg' => '学员答题卡插入成功',
                    'ver' => '1.5.0',
                    'data' => array_merge(array('mongoDate'=>$mongoDate),array('loginData'=>$loginData)),
                    'code' => '200',
                ];
            }else{
                $transaction->rollBack();
                $result = [
                    'msg' => '学员答题卡插入失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '500'
                ];
            }
            
            Yii::$app->end(json_encode($result));
            } catch (Exception $e) {
                $transaction->rollBack();
                $result = [
                    'msg' => '学员答题卡插入失败1',
                    'ver' => '1.5.0',
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }
    //组课教师退课功能
    public function actionDropoutCourseOrganize(){
        $course_id = empty($_REQUEST['course_id'])?$error[]=array('课程ID不能为空'):$_REQUEST['course_id'];
        $author_id = empty($_REQUEST['author_id'])?$error[]=array('组课教师ID不能为空'):$_REQUEST['author_id'];
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $sql="update b_course_author set del_flag=1,update_by=:author_id,update_time=:update_time where t_course_info_id=:courseId and t_base_user_id=:author_id and is_creater=0";
            $res=\yii::$app->db->createCommand($sql)->bindValues([':author_id'=>$author_id,':update_time'=>date('Y-m-d H:i:s',time()),':courseId'=>$course_id])->execute();
            if($res){
                //退课成功
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200',
                ];
            }else{
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '400',
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    //审核教师退课功能
    public function actionDropoutCourseReview(){
        $course_id = empty($_REQUEST['course_id'])?$error[]=array('课程ID不能为空'):$_REQUEST['course_id'];
        $author_id = empty($_REQUEST['author_id'])?$error[]=array('组课教师ID不能为空'):$_REQUEST['author_id'];
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601',
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $sql="update b_examine set del_flag=1,update_by=:author_id,update_time=:update_time where t_course_info_id=:courseId and t_base_user_id=:author_id";
            $res=\yii::$app->db->createCommand($sql)->bindValues([':author_id'=>$author_id,':update_time'=>date('Y-m-d H:i:s',time()),':courseId'=>$course_id])->execute();
            if($res){
                //退课成功
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200',
                ];
            }else{
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '400',
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
}
